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

标签 c++ arrays include

我创建了 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/

相关文章:

c++ - 在 C++ 中读取/写入设备

javascript - 如何扩展 Array.prototype.push()?

arrays - 在 Swift 中创建数组

c++ - 通过引用为 boost::shared_ptr 创建别名

c++ - '打开文件名': undeclared identifier

c++ - 多源 .cpp 文件问题

include - 在MPLAB X IDE中使用外部头文件

php - 在 PHP 中使用与包含

c++ - mysqlpp::Query::store() 上的 MySQL++ malloc_error_break

c++ - 如何将整个 char 数组及其值传递给另一个函数?