2013-04-05 72 views
4

我创建了2个类,分支和帐户,并且我希望我的Branch类具有一个帐户指针数组,但我无法执行此操作。它说“不完整的类型是不允许的”。我的代码有什么问题?尝试创建指针数组时不允许使用不完整类型

#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--------------*/ 
    }; 
+2

数组在编译时是否已知大小?另外,你确定你需要'Account'指针,而不仅仅是对象吗? – chris 2013-04-05 01:22:11

+0

开始时数组的大小为0,我将动态扩展它。是的,我需要帐户指针,因为帐户对象的数组是在另一个文件,我需要指出它也从另一个类名为客户。 – 2013-04-05 01:27:04

+0

我不明白你的意思。首先,你可以使用一个'std :: vector'来完成调整大小和一切。关于你的结构,如果'Customer.h'和'Branch.h'包含'Account.h',它们都可以使用普通对象。没有指针需要。 – chris 2013-04-05 01:33:33

回答

9

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

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

考虑到Account类的应用,我认为使用比c样式原始数组更好的容器是一个好主意,它具有便利功能和类似的东西。另外它不需要手动删除。 – dtech 2013-04-05 01:39:44

+0

@ddriver这是绝对正确的。但是,这个代码看起来像是一个学习任务,所以OP还没有研究容器。 – dasblinkenlight 2013-04-05 01:41:26

+0

好吧,我强调**你必须遵循三五个规则**。当它不起作用时不要回来,因为你忽略了它。 – chris 2013-04-05 01:43:52

3

你需要指定数组的大小...你不能就这么走挂在那里的托架没有任何东西在里面。