一系列不同的对象

时间:2013-04-08 19:59:20

标签: c++ arrays

好吧,我正在努力做的基本上就是这个。

我有一个Account类,然后我有一个从Account类继承的CheckingAccount和SavingsAccount类。

在我的程序中,我有一个名为accounts的数组。它将保留两种类型帐户的对象。

Account** accounts;
accounts = new Account*[numAccounts];


accountFile >> tempAccountNum >> tempBalance >> tempTransFee;
CheckingAccount tempAccount(tempBalance, tempAccountNum, tempTransFee);
accounts[i] = tempAccount;

尝试将tempAccount分配给accounts数组时出错。

从“CheckingAccount”到“帐户”没有合适的转换功能。

如何使帐户数组包含两种对象?

2 个答案:

答案 0 :(得分:3)

accounts中的每个元素都是Account*。也就是说,“指向Account”的指针。您正在尝试直接分配Account。相反,您应该使用该帐户的地址:

accounts[i] = &tempAccount;

请记住,tempAccount超出范围后,此指针将指向无效对象。

考虑避免使用数组和指针。除非你有充分的理由不这样做,否则我会使用std::vector Account s(Account* s):

std::vector<Account> accounts;

accountFile >> tempAccountNum >> tempBalance >> tempTransFee;
accounts.emplace_back(tempBalance, tempAccountNum, tempTransFee);

答案 1 :(得分:0)

我认为您需要将tempAccount的地址分配到accounts数组中。

accounts [i] =&amp; tempAccount;

因为在处理C ++中的多态时,使用对象的地址而不是对象本身。