首页 > 解决方案 > C++ 方法声明不兼容

问题描述

这是一个用于二叉树的简单 C++ 类。编译器抛出错误:

E0147 声明与“void BinaryTree::getLeftChild(node *n)”不兼容

node是在类中的部分下定义的结构private。我不确定为什么它说不兼容的声明。

//------------------------ BinaryTree class-----------------
class BinaryTree
{
public:
    BinaryTree();
    ~BinaryTree();
    void createRootNode();
    void getChildren();
    void getLeftChild(node* n);
    void getRightChild(node* n);

private:
    typedef struct node
    {
        node *lchild = nullptr;
        int data;
        node *rchild = nullptr;
    }node;

    queue <node*> Q;
    node *root; 
};

BinaryTree::BinaryTree()
{
    createRootNode();
    getChildren();
}

void BinaryTree::createRootNode()
{
    root = new node();
    cout << "Enter value for root node" << endl;
    cin >> root->data;
    Q.push(root);
}

void BinaryTree::getChildren()
{
    while (Q.empty == false)
    {
        getLeftChild(Q.front());
        getRightChild(Q.front());
        Q.pop();
    }
}

void BinaryTree::getLeftChild(node* n)
{

}

void BinaryTree::getRightChild(node* n)
{

}

有错误的代码图片

图片

标签: c++classstructprivate

解决方案


我在全局范围内得到了另一个结构,声明为“节点”,这造成了混乱。其次,我还需要修复公共和私人部分的顺序。

这是工作代码

    //------------------------ BinaryTree class-----------------
class BinaryTree
{
private:
    typedef struct node
    {
        node *lchild = nullptr;
        int data;
        node *rchild = nullptr;
    }node;

    queue <node*> Q;
    node *root;

public:
    BinaryTree();
    ~BinaryTree();
    void createRootNode();
    void getChildren();
    void getLeftChild(node* n);
    void getRightChild(node* n);
};

BinaryTree::BinaryTree()
{
    createRootNode();
    getChildren();
}

void BinaryTree::createRootNode()
{
    root = new node();
    cout << "Enter value for root node" << endl;
    cin >> root->data;
    Q.push(root);
}

void BinaryTree::getChildren()
{
    while (Q.empty() == false)
    {
        getLeftChild(Q.front());
        getRightChild(Q.front());
        Q.pop();
    }
}

void BinaryTree::getLeftChild(node* n)
{

}

void BinaryTree::getRightChild(node* n)
{

}

推荐阅读