【问题标题】:error: no matching function for call to ‘BSTreeNode<int, int>::BSTreeNode(int, int, NULL, NULL)’ - what's wrong?错误:没有匹配函数调用‘BSTreeNode<int, int>::BSTreeNode(int, int, NULL, NULL)’ - 怎么了?
【发布时间】:2010-12-25 06:25:53
【问题描述】:

错误:没有匹配的调用函数 到 'BSTreeNode::BSTreeNode(int, int, NULL, 空)’

候选人是: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){}

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

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

【问题讨论】:

    标签: c++ templates constructor


    【解决方案1】:

    非 const 引用不能绑定到右值,这是您尝试对 DT &amp;data 参数的参数 9 执行的操作。

    您需要传入一个值为9 的变量,或者您需要将参数(以及dataItem 成员,如果它是引用)更改为DT 类型按值复制到对象中。即使您将引用更改为const 以消除编译器错误,如果传入的参数是临时的(它不会在构造函数调用之后存在,所以您会遇到传入参数的生命周期问题,因此你会留下一个悬空的参考)。

    这是一个小示例程序,演示了将对象中的 const 引用绑定到临时对象(从 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
    

    【讨论】:

    • 非常感谢伯尔先生。这为我节省了很多时间......当我现在看它时,这是一个愚蠢的错误,但很容易错过。
    • 你能对生命周期问题多加一点解释吗?
    猜你喜欢
    • 2020-07-02
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 2012-06-18
    • 2011-04-03
    • 1970-01-01
    相关资源
    最近更新 更多