无法动态初始化类中的数组,除非大小 var 在类之外

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

本文关键字:var 动态 初始化 数组      更新时间:2023-10-16

我正在将 C 代码移植到 C++ 并且我在动态数组初始化时遇到了问题。下面的代码是该问题的简化版本。为什么如果在类中声明了 maxSize,但在类外部声明则没问题,为什么会出现错误?

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

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

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

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

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

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

问题是与 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;
}

另一种选择:

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

    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...
};