无法动态初始化类中的数组,除非大小 var 在类之外
Unable to dynamically initialize array within a class unless size var is outside the class
我正在将 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::vector
。 Node
类不需要使用动态分配的内存:
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...
};
相关文章:
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- C++中的动态铸造故障
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 内联映射初始化的动态atexit析构函数崩溃
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 控制允许动态运行c++的并发操作数
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 输出没有重复元素的动态数组(收缩数组)C++
- C++为线程工作动态地分割例程
- 正在插入动态数组
- 在c++中使用动态分配的问题
- C++中的动态对象与非动态对象
- 如何在动态数组上使用搜索函数
- 视觉studo 2019中的漫画和静态/动态绑定
- 从C++中的数字输入动态创建矩阵
- 如何从QToolBox中动态创建的QLineEdit中获取文本
- C++ 动态数组每次添加时将大小增加 1 - 错误
- 无法动态初始化类中的数组,除非大小 var 在类之外