c++ - 错误 : no matching function for call to ‘BSTreeNode<int, int>::BSTreeNode(int, int, NULL, NULL)’ - what's wrong?

标签 c++ templates constructor

error: no matching function for call to ‘BSTreeNode::BSTreeNode(int, int, NULL, NULL)’

candidates are: BSTreeNode::BSTreeNode(KF, DT&, BSTreeNode*, BSTreeNode*) [with KF = int, DT = int]

我是这样用的:

BSTreeNode<int, int> newNode(5,9, NULL, NULL) ;

我是这样定义的:

BSTreeNode(KF sKey, DT &data, BSTreeNode *lt, BSTreeNode *rt):key(sKey),dataItem(data), left(lt), right(rt){}

以这种方式使用我的构造函数有什么问题?

我整晚都在拔头发,请尽快帮帮我!!

最佳答案

非常量引用不能绑定(bind)到右值,这就是您要对 DT &data 参数的参数 9 所做的。

您要么需要传入一个值为 9 的变量,要么您需要更改参数(以及 dataItem 成员,如果它是reference) 为 DT 类型,按值复制到对象中。即使您将引用更改为 const 以消除编译器错误,如果传入的参数是临时的(它不会超过构造函数调用,所以你会留下一个悬垂的引用)。

这是一个小示例程序,演示了将对象中的 const 引用绑定(bind)到临时对象(从 rand() 返回的 int 值)时出现的问题。请注意,该行为是未定义的,因此它可能在某些条件下看起来有效。我在 MSVC 2008 和 MinGW 4.5.1 上使用调试版本测试了这个程序:

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>

template <class KF, class DT>
class BSTreeNode {

private:
    KF key;
    DT const& dataItem;
    BSTreeNode* left;
    BSTreeNode* right;

public:
    BSTreeNode(KF sKey, DT const &data, BSTreeNode *lt, BSTreeNode *rt)
        : key(sKey)
        , dataItem(data)
        , left(lt)
        , right(rt)
    {}

    void foo() {
        printf( "BSTreeNode::dataItem == %d\n", dataItem);
    } 
};

BSTreeNode<int, int>* test1()
{
    BSTreeNode<int, int>* p = new BSTreeNode<int, int>(5,rand(), NULL, NULL);

    // note: at this point the reference to whatever `rand()` returned in the
    //  above constructor is no longer valid
    return p;
}


int main()
{
    BSTreeNode<int, int>* p1 = test1();

    p1->foo();

    printf( "some other random number: %d\n", rand());

    p1->foo();
}

运行示例显示:

BSTreeNode::dataItem == 41
some other random number: 18467
BSTreeNode::dataItem == 2293724

关于c++ - 错误 : no matching function for call to ‘BSTreeNode<int, int>::BSTreeNode(int, int, NULL, NULL)’ - what's wrong?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4529508/

相关文章:

c++ - 如何在Linux中获取mmap()函数的FileDescriptor的内存地址,对于Video4Linux

php - 将 RSS feed 添加到 Codeigniter 中 View 的一部分

c++ - 如何处理相互依赖且具有模板成员的类?

c++ - 抽象类和唯一指针

c++ - 用大括号调用构造函数

c++ - 如何指定为成员字段对象调用哪个构造函数?

c++ - 如何避免 ncurses 中的 stdscr 重叠?

c++ - 无序集,是否值得在插入前调用查找?

C++ 和 C 文件 I/O

c++ - 在 C++ 模板代码中找不到构造函数