不同对象的数组
Array of different objects
我要做的就是。
我有一个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++中处理多态性时,使用的是对象的地址,而不是对象本身。
相关文章:
- 销毁C++中动态分配的内存(数组对象)
- 数组对象的生存期是否在重用其元素存储时结束?
- 为什么顶点数组对象会导致错误?
- 具有纯虚函数和指针数组对象类型的父类的指针数组
- 这是使用构造函数初始化数组对象的最佳方法吗?
- OpenGL 顶点数组对象与 tinyobjloader
- 将数组/对象/结构列表从C#库中传递给C MFC应用程序
- C++ RapidJson 帮助反序列化数组对象
- ptrdiff_t可以表示指向同一数组对象元素的指针的所有减法吗?
- 检查成员函数是否返回临时对象或数组对象
- 为什么 std::variant 不能容纳数组对象类型,而联合可以?
- 当数组对象以函数参数传递时,为什么复制构造函数会自称
- 如何使用箭头指针打印出一类数组对象,这些对象中有多个分数
- C++17 std::shared_ptr<> 类数组对象的重载运算符 []
- 添加两个具有运算符重载的数组对象,从而导致分段错误
- opengl:两个不同的矢量可以绑定到同一个顶点数组对象吗
- 使用相同的数据填充数组对象或使用指针
- 方法用于最快的分配,并且不需要将动态大小的数组对象作为局部变量
- 如何将2d数组对象传递给c++中的函数
- ReferenceTable溢出(jni-android),数组对象释放