Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 不同对象的数组_C++_Arrays - Fatal编程技术网

C++ 不同对象的数组

C++ 不同对象的数组,c++,arrays,C++,Arrays,好吧,我想做的基本上就是这样 我有一个Account类,然后我有一个CheckingAccount和SavingsAccount类,它们继承自Account类 在我的程序中,我有一个名为accounts的数组。它将保存这两种类型帐户的对象 Account** accounts; accounts = new Account*[numAccounts]; accountFile >> tempAccountNum >> tempBalance >> temp

好吧,我想做的基本上就是这样

我有一个Account类,然后我有一个CheckingAccount和SavingsAccount类,它们继承自Account类

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

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


accountFile >> tempAccountNum >> tempBalance >> tempTransFee;
CheckingAccount tempAccount(tempBalance, tempAccountNum, tempTransFee);
accounts[i] = tempAccount;
尝试将tempAccount分配给accounts数组时出错

不存在从“CheckingAccount”到“Account”的适当转换函数


如何使accounts数组同时容纳这两种对象?

accounts中的每个元素都是一个
Account*
。即“指向
帐户的指针”。您正试图直接分配一个
帐户。相反,您应该记下该帐户的地址:

accounts[i] = &tempAccount;
请记住,一旦
tempAccount
超出范围,此指针将指向无效对象

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

std::向量账户;
accountFile>>tempAccountNum>>tempBalance>>诱惑转移;
账户。重新安置(临时余额、临时账户数量、转移);

账户中的每个元素都是一个账户*
。即“指向
帐户的指针”。您正试图直接分配一个
帐户。相反,您应该记下该帐户的地址:

accounts[i] = &tempAccount;
请记住,一旦
tempAccount
超出范围,此指针将指向无效对象

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

std::向量账户;
accountFile>>tempAccountNum>>tempBalance>>诱惑转移;
账户。重新安置(临时余额、临时账户数量、转移);

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

账户[i]=&临时账户


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

< P>我认为您需要将TunCube的地址分配到帐户数组中。 账户[i]=&临时账户


因为在处理C++中的多态性时,你使用的是对象的地址而不是对象本身。一旦我关闭我的帐户文件。帐户数组变为空。关闭文件后,我如何将这些对象保留在数组中?@user2234688您应该发布一个新问题。我不是在回避它——这只是这里的一般做法!好吧,现在我遇到了你说的我最终会遇到的问题。一旦我关闭我的帐户文件。帐户数组变为空。关闭文件后,我如何将这些对象保留在数组中?@user2234688您应该发布一个新问题。我不是在回避它——这只是这里的一般做法!