C++ 尝试创建指针数组时不允许使用不完整的类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15824408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
incomplete type is not allowed while trying to create an array of pointers
提问by Burak ?zmen
I created 2 classes, Branch and Account and I want my Branch class have an array of Account pointers, but i fail to do it. It says that "incomplete type is not allowed". What is wrong with my code?
我创建了 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--------------*/
};
回答by dasblinkenlight
Although you can create an array of pointers to forward-declared classes, you cannot create an array with an unknown size. If you want to create the array at runtime, make a pointer to a pointer (which is of course also allowed):
尽管您可以创建一个指向前向声明类的指针数组,但您不能创建一个大小未知的数组。如果要在运行时创建数组,请创建一个指向指针的指针(当然也是允许的):
Account **ownedAccounts;
...
// Later on, in the constructor
ownedAccounts = new Account*[numOwnedAccounts];
...
// Later on, in the destructor
delete[] ownedAccounts;
回答by 2to1mux
You need to specify the size of the array... You can't just leave the brackets hanging like that without anything inside them.
您需要指定数组的大小...您不能像这样挂起括号而没有任何内容。