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

标签 c++ recursion

我从一棵 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/

相关文章:

c++ - 检查文件格式正确性的最佳方法

c++ - CMake 库目标并不总是出现在 Visual Studio 2017 的启动项下拉列表中

c++ - 如何在 Linux 上部署 C++ 应用程序

recursion - 带外部变量的递归函数

c++ - 递归回文测试

c# - 用于重命名冲突默认值的 ProtoEnum 属性用法

c++ - 为什么这段代码不打印我的数组?

java - Arraycopy 使我的程序崩溃

java - 由于线程挂起而导致递归问题

java - 如何避免在递归中重复检查?