gpt4 book ai didi

c++ - 错误 : Invalid use of non-static data member, 变量未在此范围内声明

转载 作者:行者123 更新时间:2023-11-27 23:56:16 25 4
gpt4 key购买 nike

以下是跳过列表的模板化类中的内部嵌套类。我在声明 *next 的行收到错误消息:“高度未在此范围内声明”。

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

将 value 和 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;}
};

我不知道该怎么做才能解决这个问题。这是整个类(class):

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 我不确定什么数据结构使用指针数组作为节点的“下一个”节点。只是一些需要考虑的事情。

关于c++ - 错误 : Invalid use of non-static data member, 变量未在此范围内声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42452965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com