完善下列代码#define N 3; class CHouse { private: char mName[20]; //地址 float mPrice; //单价 float mArea; //面积 public: float getprice() { return mPrice; } float getarea() { return mArea; } void set(char* name, float price, float area); //修改房屋参数 CHouse(char* name=0,float price=0,float area=0); //构造函数 friend ifstream& operator>> (ifstream &is, CHouse &house); //从文件中读取一个房屋参数 friend ostream& operator<< (ostream &is, CHouse &house); }; class CBuilding //大楼 { private: CHouse *mHouse; int mNums; int size; public: CBuilding(int m = N) { mHouse = new CHouse[m]; size = m; mNums = 0; } float Total(); //计算大楼所有房屋的总价值 void AddHouse(char* name,float price,float area); //加入房屋到大楼中,注意空间是否超出 void ReadData(char* filename); //将大楼信息从文件中读取 friend ostream& operator<< (ostream &is, CBuilding & cb); ~CBuilding(); }; void main() { CBuilding Building; Building.ReadData("data.txt"); Building.AddHouse("507",23000,80); cout<<Building<<endl; }
时间: 2024-03-15 18:45:55 浏览: 51
各种单片机的比较(avr 8051 stc 等)
这段代码中存在一个问题:在宏定义 N 的后面有一个分号,应该将它改为:
```
#define N 3
```
另外,还需要完善 CHouse 类中的 set 方法和构造函数,代码如下:
```cpp
void set(char* name, float price, float area)
{
strcpy(mName, name);
mPrice = price;
mArea = area;
}
CHouse(char* name = 0, float price = 0, float area = 0)
{
if (name != 0)
{
strcpy(mName, name);
}
mPrice = price;
mArea = area;
}
```
在 CBuilding 类中,需要完善 AddHouse 方法、Total 方法、<< 运算符重载函数和析构函数。具体代码如下:
```cpp
void AddHouse(char* name, float price, float area)
{
if (mNums >= size)
{
cout << "Add Error: The building is full!" << endl;
return;
}
mHouse[mNums++].set(name, price, area);
}
float Total()
{
float total = 0;
for (int i = 0; i < mNums; i++)
{
total += mHouse[i].getprice() * mHouse[i].getarea();
}
return total;
}
ostream& operator<<(ostream& os, CBuilding& cb)
{
os << "Building Info: " << endl;
for (int i = 0; i < cb.mNums; i++)
{
os << "House " << i + 1 << ": " << cb.mHouse[i].getprice() << " * " << cb.mHouse[i].getarea() << " = " << cb.mHouse[i].getprice() * cb.mHouse[i].getarea() << endl;
}
os << "Total Value: " << cb.Total() << endl;
return os;
}
CBuilding::~CBuilding()
{
delete[] mHouse;
}
```
阅读全文