不同对象的数组

Array of different objects

本文关键字:数组 对象      更新时间:2023-10-16

我要做的就是。

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

在我的程序中,我有一个名为accounts的数组。它将保存两种类型的帐户的对象。
Account** accounts;
accounts = new Account*[numAccounts];

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

我得到一个错误时,试图分配tempAccount帐户数组。

没有合适的从"CheckingAccount"到"Account"的转换功能。

如何使account数组同时包含两种对象?

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

accounts[i] = &tempAccount;

请记住,一旦tempAccount超出作用域,这个指针将指向一个无效的对象。

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

std::vector<Account> accounts;
accountFile >> tempAccountNum >> tempBalance >> tempTransFee;
accounts.emplace_back(tempBalance, tempAccountNum, tempTransFee);

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

accounts[i] = &tempAccount;

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