gpt4 book ai didi

c++ - 尝试创建指针数组时不允许使用不完整的类型

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:57:57 29 4
gpt4 key购买 nike

我创建了 2 个类,Branch 和 Account,我希望我的 Branch 类有一个 Account 指针数组,但我没能做到。它说“不允许不完整的类型”。我的代码有什么问题?

#include <string>
#include "Account.h"

using namespace std;



class Branch{

/*--------------------public variables--------------*/
public:
Branch(int id, string name);
Branch(Branch &br);
~Branch();
Account* ownedAccounts[]; // error at this line
string getName();
int getId();
int numberOfBranches;
/*--------------------public variables--------------*/

/*--------------------private variables--------------*/
private:
int branchId;
string branchName;
/*--------------------private variables--------------*/
};

最佳答案

虽然您可以创建指向前向声明类的指针数组,但您不能创建大小未知的数组。如果想在运行时创建数组,做一个指向指针的指针(当然也是允许的):

Account **ownedAccounts;
...
// Later on, in the constructor
ownedAccounts = new Account*[numOwnedAccounts];
...
// Later on, in the destructor
delete[] ownedAccounts;

关于c++ - 尝试创建指针数组时不允许使用不完整的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15824408/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com