试图用C ++声明一个成员对象

时间:2013-05-25 14:34:27

标签: c++ list object initialization member

我正在尝试用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;

}

我得到了这些错误:

  • sytax错误:缺少';'在标识符'homeBranch'之前
  • 缺少类型说明符 - 假设为int(因为它显然是一个对象而感到困惑?)
  • 'bankAccount':非法成员初始化:'homebranch'不是基础或成员

我已经尝试过很多东西而且似乎无法修复这些错误,是否有人可以向我提供一些有关如何正确添加member-object bankBranch homeBranch到类bankAccount的见解?以及如何正确使用初始化列表。

1 个答案:

答案 0 :(得分:2)

您需要在此文件中包含定义bankBranch的头文件(而不是翻译单元)。

由于您正在使用组合并创建bankBranch的成员,因此编译器需要知道bankBranch实例所需的布局和内存的详细信息,此信息只能通过了解定义来获取bankBranch。请注意,前向声明在这里是不够的。