递归成员函数无法访问自己的变量
Recursive member function can't access its own variables
我从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;
我和安德烈有同样的看法;我也不喜欢使用向量作为子节点容器。如果数据结构是一个简单的二叉树,为什么不直接使用
呢?Node* leftChild;
Node* rightChild;
作为类Node的数据成员?
另外,请提供创建树的代码。很可能你在那里犯了一些错误,因为分割错误很可能是由于数据结构的创建不当,你可能没有意识到这一点。
-
乍一看,似乎你的树的最后一层必须只包含数字。 -
实际上,我不喜欢向量作为儿童容器。为什么不用两个指针呢?此外,我不知道你在哪里初始化向量并将子向量放入其中。
-
看看
rand()
是如何工作的
您从未检查您的节点是否有任何子节点。
相关文章:
- 没有为自己的结构调用列表推回方法
- C++:无法访问声明的受保护成员
- 如何正确实现和访问运算符的各种自定义枚举器
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 链表中写入访问冲突的未知原因
- 如何访问RTCVideoRenderer的帧?(ios)
- 类无法访问自己的私有静态 constexpr 方法 - Clang bug?
- 如何访问模板参数自己的模板参数?
- 访问另一个类(系统)的非静态字段,就好像它是我自己的字段一样 - 优雅地
- 何时使用'this'访问自己的成员
- 如何从公共变量自己的类成员函数中访问它们?(C++)
- 我是否可以像访问自己的对象一样访问对象的'base part'?
- 实例是否应该使用资源库/获取器来访问自己的私有数据成员
- 在AD中尝试更新我自己的字段时,一般访问被拒绝
- ctypes 自己的库加载,但无法访问函数/方法
- 为什么无法从模板方法访问此类自己的受保护成员?
- 如何使从基类继承的对象访问字符方法,但有自己的结果
- 递归成员函数无法访问自己的变量
- 循环问题:从它自己的成员函数中访问一组对象
- 类对象作为参数传递,访问它们自己的私有成员