gpt4 book ai didi

c++ - 递归成员函数不能访问自己的变量

转载 作者:行者123 更新时间:2023-11-28 08:16:59 24 4
gpt4 key购买 nike

我从一棵 5 层深的树的顶部节点开始,并在每个节点上递归调用 getvalue()。每个节点都链接到下一层的两个节点。我很确定这不是我的问题,因为我在纸上仔细检查了算法。然而,一旦我到达第 3 层,它就会给我一个段错误。使用 valgrind,我发现它是在我尝试打印类变量 oper 时引发的。我不知道该去哪里,所以非常感谢您的帮助。这是代码:

class Node {
public:
vector<Node> children;
long constval;
char oper;
void setconst();
Node();
void copy(const Node*);
int getvalue();
private:
int mult(int,int);
int div(int,int);
int add(int,int);
int sub(int,int);
};

Node::Node() {
bool c = false;
vector<char> operations;
operations.push_back('m');
operations.push_back('a');
operations.push_back('s');
operations.push_back('d');
operations.push_back('c');
constval = rand();
int randnum = rand() % 5;
cout << randnum << "\n";
oper = operations[randnum];
}

int Node::getvalue() {
cout << oper << '\n';
if (oper == 'm') {
return Node::mult(children[0].getvalue(), children[1].getvalue());
}
else if (oper == 'd') {
return Node::div(children[0].getvalue(), children[1].getvalue());
}
else if (oper == 'a') {
return Node::add(children[0].getvalue(), children[1].getvalue());
}
else if (oper == 's') {
return Node::sub(children[0].getvalue(), children[1].getvalue());
}
else if (oper == 'c') {
return constval;
}
}

编辑:这是我的初始化算法:

class Individual {
public:
vector< vector<Node> > nodes;
vector< vector<Node> > getrand();
void replace(vector< vector<Node> >);
void mutate(double);
double run();
Individual();
};

Individual::Individual() {
nodes.resize(5);
nodes[0].resize(1);
int size = 2;
for(int i = 1; i < 5; i++) {
nodes[i].resize(size);
size = size * 2;
}
vector<char> operations;
operations.push_back('a');
operations.push_back('s');
operations.push_back('d');
operations.push_back('m');
nodes[0][0].oper = operations[rand() % 4];
for(int x = 0; x < nodes[4].size(); x++) {
nodes[4][x].setconst();
}
for(int i = 0; i < 4; i++) {
for(int x = 0; x < nodes[i].size(); x++) {
nodes[i][x].children.push_back(nodes[i+1][x*2]);
nodes[i][x].children.push_back(nodes[i+1][x*2+1]);
}
}
}

最佳答案

vector<Node> children;

我和安德烈的看法相同;我也不喜欢使用 vector 作为子节点容器。如果你的数据结构是一个简单的二叉树,为什么不简单地使用

Node* leftChild;
Node* rightChild;

作为 Node 类的数据成员?

此外,请提供创建树的代码。您可能在那里犯了一些错误,因为段错误很可能是由于数据结构创建不当造成的,而您可能没有意识到这一点。

关于c++ - 递归成员函数不能访问自己的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7396649/

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