【问题标题】:incomplete type is not allowed while trying to create an array of pointers尝试创建指针数组时不允许不完整类型
【发布时间】:2013-03-27 07:21:29
【问题描述】:

我创建了 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 指针,而不仅仅是对象吗?
  • 那行没有错误,使用 g++。演示:ideone.com/wczznf 因为我没有"Account.h",所以我写了:class Account;
  • 数组大小一开始是0,我会动态扩展。是的,我需要 Account 指针,因为 Account 对象的数组在另一个文件中,我还需要从另一个名为 Customer 的类中指向它。
  • 我不明白你的意思。首先,您可以使用std::vector 来调整大小和一切。关于你的结构,如果Customer.hBranch.h 都包含Account.h,那么它们都可以正常使用普通对象。不需要指针。
  • 我们不允许使用std::vector。至于我的结构,我脑子里有点复杂,我也无法解释。

标签: c++ arrays include


【解决方案1】:

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

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

【讨论】:

  • 考虑到 Account 类的应用,我认为使用比 c 风格的原始数组更好的容器是个好主意,它具有方便的功能和类似的东西。另外它不需要手动删除。
  • @ddriver 这绝对是真的。但是,有问题的代码看起来像是一个学习任务,所以 OP 可能还没有研究过容器。
  • 好吧,我强调您必须遵守三五规则。当它不起作用时不要回来,因为你忽略了它。
  • 实际上,内存泄漏在我们的赋值中是不可接受的,所以我将使用析构函数、构造函数和复制构造函数。
  • 还有赋值运算符,可能还有移动构造函数和移动赋值运算符。
【解决方案2】:

你需要指定数组的大小...你不能让括号像这样悬空,里面没有任何东西。

【讨论】:

  • 你能详细说明一下吗,考虑到这里的例子cplusplus.com/doc/tutorial/arraysint firstarray[]的空括号
  • 这是对我有帮助的答案。有趣的是,在堆栈上实例化数组时不指定大小有效,但在类声明的一部分时无效。虽然理由是有道理的,但这让我有点惊讶。
猜你喜欢
  • 2021-12-31
  • 2012-08-15
  • 2015-10-09
  • 1970-01-01
  • 2017-10-28
  • 1970-01-01
  • 2015-05-07
  • 1970-01-01
相关资源
最近更新 更多