我正在尝试用C ++在类中声明一个成员对象,如下所示:
class bankAccount
{
public:
bankAccount(int, int, int, string, int);
private:
bankBranch homeBranch;
};
bankAccount::bankAccount(int accountNumber, int accountBalance, int homebsbnumber,
string homeaddress, int homepostcode) : homeBranch(homebsbnumber, homeaddress, homepostcode) {}
class bankBranch
{
public:
/** bankBranch(const int& bsbNumber, const string& address, const int& postCode)
{
this->bsbNumber = bsbNumber;
this->address = address;
this->postCode = postCode;
}; **/
bankBranch(int, string, int);
void setPostCode()
{
cout << "Please type in the postal code of your bankBranch: " << endl;
cin >> postCode;
}
void setBsbNumber()
{
cout << "Please type in the BSB Number of your bankBranch: " << endl;
cin >> bsbNumber;
}
void setAddress()
{
cout << "Please type in the address of your bankBranch " << endl;
cin >> address;
}
// Return methods for bsb number, address and post code
int getBsbNumber()
{
return this->bsbNumber;
}
string getAddress()
{
return this->address;
}
int getPostCode()
{
return this->postCode;
}
private:
int bsbNumber;
string address;
int postCode;
};
bankBranch::bankBranch(int bsbnum, string bankaddress, int bankpostcode) {
bsbNumber = bsbnum;
address = bankaddress;
postCode = bankpostcode;
}
我得到了这些错误:
我已经尝试过很多东西而且似乎无法修复这些错误,是否有人可以向我提供一些有关如何正确添加member-object bankBranch homeBranch到类bankAccount的见解?以及如何正确使用初始化列表。
答案 0 :(得分:2)
您需要在此文件中包含定义bankBranch
的头文件(而不是翻译单元)。
由于您正在使用组合并创建bankBranch
的成员,因此编译器需要知道bankBranch
实例所需的布局和内存的详细信息,此信息只能通过了解定义来获取bankBranch
。请注意,前向声明在这里是不够的。