错误:非静态数据成员的使用无效,在此范围内未声明变量
Error: Invalid use of non-static data member, variable was not declared in this scope
以下是Skiplist模板类中的内部嵌套类。我遇到了错误:"在此范围中没有声明"高度"在"宣布 *"的行中。
class Node{
public:
Node(int height){
this->height = height;
}
Node(Key_t key, Mapped_t obj, int height){
value = std::make_pair(key, obj);
this->height = height;
}
SkipList<Key_t, Mapped_t>::Node *next[height];
int getHeight(){return height;}
Key_t getKey(){return value.first;}
Mapped_t getObj(){return value.second;}
private:
std::pair<Key_t, Mapped_t> value;
int height;
};
如下 class Node{
private:
std::pair<Key_t, Mapped_t> value;
int height;
public:
Node(int height){
this->height = height;
}
Node(Key_t key, Mapped_t obj, int height){
value = std::make_pair(key, obj);
this->height = height;
}
SkipList<Key_t, Mapped_t>::Node *next[height];
int getHeight(){return height;}
Key_t getKey(){return value.first;}
Mapped_t getObj(){return value.second;}
};
,我对解决这个问题的操作感到不知所措。这是整个课程:
template <class Key_t, class Mapped_t>
class SkipList{
public:
SkipList(int prob, int max){
probOutOf100 = prob;
maxHeight = max;
head = new SkipList<Key_t, Mapped_t>::Node(maxHeight);
tail = new SkipList<Key_t, Mapped_t>::Node(maxHeight);
for(int i = 0; i < maxHeight; i++){
head->next[i] = tail;
}
}
~SkipList(){
delete head;
delete tail;
}
class Node{
public:
Node(int height){
this->height = height;
}
Node(Key_t key, Mapped_t obj, int height){
value = std::make_pair(key, obj);
this->height = height;
}
SkipList<Key_t, Mapped_t>::Node *next[height];
int getHeight(){return height;}
Key_t getKey(){return value.first;}
Mapped_t getObj(){return value.second;}
private:
std::pair<Key_t, Mapped_t> value;
int height;
};
Node *head;
Node *tail;
int probOutOf100;
int maxHeight;
}
的行中
SkipList<Key_t, Mapped_t>::Node *next[height];
您正在尝试声明一系列指针。但是,除非height
在编译时已知,否则您不能这样做。
您可能需要将其更改为vector
并在运行时进行初始化。
std::vector<SkipList<Key_t, Mapped_t>::Node*> next;
...
Node(int height) : next(height) {
this->height = height;
}
ps 我不确定哪种数据结构使用了哪种指针作为节点的"下一个"节点。只是要考虑的东西。
问题1
您无法使用编译器尚未看到的内容,因此将声明上方移动来解决此问题。您已经完成了。好工作。
问题2
height
直到对象构造后才知道。如果对象的大小未知,则无法构造对象,并且height
确定有助于对象大小的next
的大小。捕获22。
建议使用std::vector
代替数组,并在构造函数成员初始化器列表中使用height
初始化向量。示例:
std::vector<SkipList<Key_t, Mapped_t>::Node *> next;
Node(int height): height(height), next(height)
{
}
Node(Key_t key, Mapped_t obj, int height):
value(std::make_pair(key, obj)),
height(height),
next(height)
{
}
相关文章:
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- c++ 变量在宏的扩展中没有在这个范围内声明
- 变量不在 lambda 的范围内
- 检查私有成员变量是否在一定范围内,如果没有调整
- 如何找到在本地范围内声明的变量的地址?
- 变量未在此范围内声明 数组线性搜索
- "... already defined in *.obj"但我没有在同一范围内两次定义任何变量
- 在 mingw64- 变量下的窗口中编译 openvpn3 时出错,未在范围内声明
- 无法在命名空间范围内分配变量
- 在标头中声明时,变量未在范围内声明
- 困惑,为什么没有在此范围内声明 c++ 全局变量
- 更改if范围内变量的类型
- 错误:非静态数据成员的使用无效,在此范围内未声明变量
- "变量"未在此范围内声明
- 错误:变量未在此范围内声明
- 通过使用全局变量的函数访问在给定范围内被覆盖的变量
- 在类范围内声明时,应在 C++14 中引用变量模板
- 处理范围内变量的内部函数
- 全局范围内变量的静态含义