帮我写成完整的代码#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; } 该类中的所有成员函数在类的外部给予实现。 CHouse类对运算符 >>重载,实现从流中获取房屋信息。 CBuilding类的ReadData函数通过调用CHouse类的运算符 >>重载函数,实现房屋信息的加载。加载文本文件data.txt需要考生先在自己在当前文件夹下建立,
时间: 2024-04-07 07:31:55 浏览: 51
c代码-http://c.jsrun.net/
完整代码如下:
#include <iostream>
#include <fstream>
using namespace std;
#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) {
strcpy(mName, name);
mPrice = price;
mArea = area;
}
CHouse(char* name = 0, float price = 0, float area = 0) {
set(name, price, area);
}
friend ifstream& operator>> (ifstream &is, CHouse &house) {
is >> house.mName >> house.mPrice >> house.mArea;
return is;
}
friend ostream& operator<< (ostream &os, CHouse &house) {
os << house.mName << " " << house.mPrice << " " << house.mArea;
return os;
}
};
class CBuilding {
private:
CHouse *mHouse;
int mNums;
int size;
public:
CBuilding(int m = N) {
mHouse = new CHouse[m];
size = m;
mNums = 0;
}
float Total() {
float sum = 0;
for (int i = 0; i < mNums; i++) {
sum += mHouse[i].getprice() * mHouse[i].getarea();
}
return sum;
}
void AddHouse(char* name, float price, float area) {
if (mNums < size) {
mHouse[mNums].set(name, price, area);
mNums++;
}
else {
cout << "The building is full!" << endl;
}
}
void ReadData(char* filename) {
ifstream fin(filename);
if (!fin.good()) {
cout << "File not exist!" << endl;
return;
}
int i = 0;
while (!fin.eof() && i < size) {
fin >> mHouse[i];
i++;
}
mNums = i;
fin.close();
}
friend ostream& operator<< (ostream &os, CBuilding &cb) {
os << "Total value: " << cb.Total() << endl;
for (int i = 0; i < cb.mNums; i++) {
os << cb.mHouse[i] << endl;
}
return os;
}
~CBuilding() {
delete[] mHouse;
}
};
int main() {
CBuilding Building;
Building.ReadData("data.txt");
Building.AddHouse("507", 23000, 80);
cout << Building << endl;
return 0;
}
阅读全文