无法在 class 内动态初始化数组,除非 size var 在 class 之外

Unable to dynamically initialize array within a class unless size var is outside the class

我正在将 C 代码移植到 C++,但我遇到了动态数组初始化问题。下面的代码是问题的简化版本。为什么在 class 内声明 maxSize 会出错,而在

外声明却没问题?

编辑:为什么没有类似于添加 static int maxSize 的简单解决方案;在 class 之外?由于很少提及的原因,这可能是不好的做法,那么下一个最佳解决方案是什么需要对 bTree class 中的其余方法进行 最少 的修改量?

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>

using std::cout;
using std::endl;
using std::string;
using std::vector;

//int maxSize = 3;

class bTree
{
private:

    int maxSize = 3; // this variable is fine outside of the class but not within it..


    struct Item{
        string key;
        string value;
    };

    struct Node{
        int count;
        vector<Item> items;
        Node **branch;

        Node() : items(maxSize + 1) // error C2327: 'bTree::maxSize' : is not a type name, static, or enumerator

        {
            branch = new Node*[maxSize + 1];  // error C2327: 'bTree::maxSize' : is not a type name, static, or enumerator
        }
    };

    // .... other variables....

public:
    bTree(int size)
    {
        maxSize = size;
    }

    ~bTree(){}

    // ...other methods...

};

int main(int argc, char *argv[])
{
    bTree *bt = new bTree(5);
    return 0;
}

问题在于,与 java 不同,内部 类 struct Node 没有指向外部 class bTree 的指针。这意味着当调用 Node 的构造函数时,没有可见变量 bTree::maxSize 可以使用。您必须显式地将 maxSize 作为参数传递给构造函数。另一种选择是使该变量成为静态变量(但在我看来它不适合您的情况,因为您希望 bTree 的不同实例使用不同的 maxSize)。

编辑: 如果您对如何在此处使用静态字段感兴趣:

class bTree
{
public:
    static void setMaxSize(int maxSize)
    {
        bTree::maxSize = maxSize;
    }
    bTree()
    {}
private:
    static int maxSize = 3;
    /* ... */
    struct Node
    {
        /* ... */
        Node()
             : items(maxSize + 1)
             , branch(new Node*[maxSize + 1])
        {}
    }
}


int main()
{
    // bTree::setMaxSize(5);
    bTree bTree;
    return 0;
}

另一个选项:

您可以将结构定义放在 class 之外并定义其类型(Item、Node)的 class 数据成员,并在 class 构造函数中初始化它们。例如:

    struct Item{
        string key;
        string value;
    };

    struct Node{
        int count;
        int maxSize;
        vector<Item> items;
        Node **branch;

        ...
    };

class bTree
{
private:

    int maxSize = 3; 
    Item item;
    Node node;

public:
    bTree(int size)
    {
        maxSize = size;
        node.maxSize = size; // OR you may call a member function or constructor of Node struct.
        ...
    }

    ~bTree(){}

    // ...other methods...

};

您正在尝试访问不在 Node class 范围内的成员。一种解决方法是类似于此:

struct Node{
     //...
        std::vector<Items> items;
        Node(int m) : items(m + 1), branch(new Node*[m]()) {}
};

另一件事是您应该尽可能使用 std::vector。您的 Node class 不需要使用动态分配的内存:

struct Node{
     //...
        std::vector<Item> items;
        std::vector<Node*> branch;
        Node(int m) : items(m + 1), branch(m) {}
};