递归成员函数无法访问自己的变量

Recursive member function can't access its own variables

本文关键字:访问 自己的 变量 成员 函数 递归      更新时间:2023-10-16

我从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的数据成员?

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

  1. 乍一看,似乎你的树的最后一层必须只包含数字。

  2. 实际上,我不喜欢向量作为儿童容器。为什么不用两个指针呢?此外,我不知道你在哪里初始化向量并将子向量放入其中。

  3. 看看rand()是如何工作的

您从未检查您的节点是否有任何子节点。