String * arr填充数据,我发送了一个公共变量而不是数组。 [英] String * arr filling with data, I sent a common variable instead of an array.
本文介绍了String * arr填充数据,我发送了一个公共变量而不是数组。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<pre>//Main function
void printBythePrice(const HousingRegister &house){
float max;
string *arr = new string[house.getnrOfHouses()];
cout << "Enter the price";
cin >> max;
house.printBythePrice(arr, max);
for (int i = 0; i < house.getnrOfHouses(); i++)
{
cout << arr[i];
}
delete[] arr;
}
//handler Functinen
void HousingRegister::printBythePrice(string *arr, float max)const {
int index = 0;
for (int i = 0; i <nrOfHouses; i++)
{
if (housing[i]->getRent() >= max)
{
arr[index] = housing[i]->toString();
index++;
}
}
}
什么我试过了:
我有修理这个打印代码的问题,但我对阵列有问题。
函数需要一个字符串* arr填充数据,但你提交的是一个公共变量而不是一个数组。
如何修复它?
What I have tried:
I have trie to fix this print code but, i have a problem with the array.
function expects a string * arr filling with data, but you submit a common variable instead of an Array.
How can i fix it?
推荐答案
CPallini似乎是对的:你的字符串指针本身并不是一个数组。可能它只是一个字符串,您可以将其字符作为子字符串访问。关于数组的一些阅读。
分配一个在你的代码中使用的字符串数组:
CPallini seems to be right: your string pointer isnt an array per se. May it is only a string and you access its chars as substring. Some reading about arrays.
Allocate an string array for the use in your code like that:
string array[COUNT];
提示:使用调试器并输出一些内容以查看
Tip: use a debugger and make some output to see what
你的代码应该可以工作。
至少,它适用于我为了让它运行而创建的虚假场景
Your code should work.
And, at least, it works in the fake scenario I created to make it run
#include <iostream>
#include <vector>
using namespace std;
class Housing
{
float rent;
string name;
public:
Housing(string name, float rent):rent(rent), name(name){}
int getRent(){return rent;}
string toString(){return name;}
};
class HousingRegister
{
int nrOfHouses;
vector<Housing * > housing;
public:
HousingRegister(int houses):nrOfHouses(houses)
{
for ( int n=0; n<houses; ++n)
{
string name = "foo";
name.append( 1, (char)('0' + n));
float rent = 1000.0f * (n+1);
housing.push_back( new Housing( name, rent ));
}
}
~ HousingRegister()
{
for (size_t n=0; n<housing.size(); ++n)
delete housing[n];
}
void printBythePrice(string *arr, float max) const;
int getnrOfHouses() const { return nrOfHouses; };
};
void printBythePrice(const HousingRegister &house){
float max;
string *arr = new string[house.getnrOfHouses()];
cout << "Enter the price";
cin >> max;
house.printBythePrice(arr, max);
for (int i = 0; i < house.getnrOfHouses(); i++)
{
cout << arr[i];
}
delete[] arr;
}
//handler Functinen
void HousingRegister::printBythePrice(string *arr, float max)const {
int index = 0;
for (int i = 0; i <nrOfHouses; i++)
{
if (housing[i]->getRent() >= max)
{
arr[index] = housing[i]->toString();
index++;
}
}
}
int main()
{
HousingRegister hr(5);
printBythePrice(hr);
}
这篇关于String * arr填充数据,我发送了一个公共变量而不是数组。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文