在尝试创建指针数组时,不允许使用不完整类型

incomplete type is not allowed while trying to create an array of pointers

本文关键字:不允许 用不完 类型 创建 指针 数组      更新时间:2023-10-16

我创建了2个类,分支和帐户,我希望我的分支类有一个帐户指针数组,但我没有做到这一点。上面写着"不完整的类型是不允许的"。我的代码有什么问题?

#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;

你需要指定数组的大小…你不能就这样把括号挂起来,里面什么也没有