错误 C2661:'node::node':没有重载函数占用 3 个参数

error C2661: 'node::node' : no overloaded function takes 3 arguments

本文关键字:node 参数 C2661 错误 重载 函数      更新时间:2023-10-16

这是一个AVL树c++程序,它有以下资源:

"TreeNode.h"
"AVLTree.h"
"AVLTree.cpp"
"Main.cpp"

我添加了一个"TreeNode.cpp",并从"AVLTree.cpp"中取出了"node::node"函数,并将其放在"TreeNode.cpp"中,包括"TreeNode.h",编译后,VS 2013抛出错误C2661行:

n = new node(x, NULL, NULL);

对应"AVLTree.cpp"中错误的函数:

void tree::insert(int x, node* &n)
{
    if (n == NULL)
        n = new node(x, NULL, NULL);
    else if (x < n->data)
    {
        insert(x, n->l);
        if (n->l != NULL && n->r != NULL && n->l->height - n->r->height == 2)
        {
            if (x < n->l->data)
                rightrotation(n);
            else
                doublerotation_leftright(n);
        }
    }
    else if (x > n->data)
    {
        insert(x, n->r);
        if (n->r != NULL && n->l != NULL && n->r->height - n->l->height == 2)
        {
            if (n->r->data < x)
                leftrotation(n);
            else
                doublerotation_leftright(n);
        }
    }
    n->height = maxi(n->l, n->r) + 1;
}
"TreeNode.cpp"

:

#include "TreeNode.h"
node::node(int x, node *newleft, node *newright, int h = 0)
{
    data = x;
    l = newleft;
    r = newright;
    height = h;
}
"AVLTree.h"

:

#include "TreeNode.h"
#pragma once
class tree
{
    public:
    tree();
    ~tree();
    void insert(int x);
    bool pop(int n);
    void printpostorder();
    void printlevelorder();
    private:
    node* head;
    node* nullnode;
    void destruct(node* n);
    node* findnode(int n);
    node* min(node* n);
    node* Bfind(int n);
    void rightrotation(node* &k2);
    void leftrotation(node* &k2);
    void doublerotation_leftright(node* &k3);
    void postorder(node* n);
    void levelorder(node* n);
    void insert(int x, node* &n);
    int maxi(node *x1, node *x2);
    void balance(node* &n);
};

问题在哪里?

编辑1:

"TreeNode.h"
#pragma once
class node
{
public:
    int data;
    node* l;
    node* r;
    int height;
    node(int x, node* newleft, node* newright, int h);
};

在node的类定义中,对应的构造函数似乎没有第四个形参的默认实参。检查类定义,并在类定义中的构造函数声明中指定默认实参,而不是在cpp文件中的构造函数定义中指定。

请考虑可以使用重载委托构造函数代替默认实参。例如

class node
{
public:
    node(int x, node *newleft, node *newright);
    node(int x, node *newleft, node *newright, int h);
    //...
//,,,
node::node(int x, node *newleft, node *newright) : node( x, newleft, newright, 0 )
{
}

AVLTree.cpp看不到TreeNode.cpp,所以它不知道node的构造函数的第四个参数是可选的。

把默认参数放在声明中,而不是定义中,这样它在使用头文件的每个翻译单元中都是可见的。