【发布时间】:2021-09-16 10:49:19
【问题描述】:
每当我尝试执行我的代码时,我的输出屏幕就会崩溃。这是问题的一部分:
为房地产定位器服务声明一个名为 House 的类。这 应包括以下信息:
- 所有者:(最多 20 个字符的字符串)
- 地址:(最多20个字符的字符串)
- 卧室:(整数)
- 价格(浮点数)
b) 声明一个包含 100 个 House 类对象的数组。
c) 编写一个函数将值读入对象的成员中 房子。
d) 编写一个驱动程序来测试数据结构和 您开发的功能。
驱动程序应将内部条目读入可用的 大批。在输入数据的代码之后,您应该编写代码 输出您输入的数据以验证它是否正确。
这是我的代码:
class House {
private:
string owner;
string address;
int bedrooms;
float price;
public:
House(string owner = "", string address = "", int bedrooms = 0, float price = 0.0)
{
this->owner = owner;
this->address = address;
this->bedrooms = bedrooms;
this->price = price;
}
void setOwner(string owner)
{
this->owner = owner;
}
void setAddress(string address)
{
this->address = address;
}
void setBedrooms(int bedrooms)
{
this->bedrooms = bedrooms;
}
void setPrice(float price)
{
this->price = price;
}
string getOwner()
{
return owner;
}
string getAddress()
{
return address;
}
int getBedrooms()
{
return bedrooms;
}
float getPrice()
{
return price;
}
void getData()
{
cout << "Enter Owner : ";
getline(cin, owner);
setOwner(owner);
cout << "Enter Address : ";
cin >> address;
setAddress(address);
cout << "Number of Bedrooms? : ";
cin >> bedrooms;
setBedrooms(bedrooms);
cout << "Price : ";
cin >> price;
setPrice(price);
cout << endl;
}
void display()
{
cout << "Owner \t Address \t Bedrooms \t Price" << endl;
cout << getOwner() << "\t" << getAddress() << "\t" << getBedrooms() << "\t" << getPrice() << "\t" << endl;
}
};
int main()
{
House* h[100];
int time = 0;
char yesorno;
do {
h[time]->getData();
h[time]->display();
cout << "Do you wish to continue ?";
cin >> yesorno;
time++;
} while (yesorno == 'y' || yesorno == 'Y');
return 0;
}
【问题讨论】:
-
你是否已经学会了如何在c++中创建类/
-
h的元素未初始化。你的意思是House h[100]? -
指令清楚地说“一个包含 100 个 House 类对象的数组”,而不是“一个包含 100 个指向 House 类对象的指针的数组”。您为什么决定不按照说明进行操作?