开发者

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

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]

here is how I used it:

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

I defined it as follows:

BSTreeNode(KF sKey, DT &am开发者_开发知识库p;data, BSTreeNode *lt, BSTreeNode *rt):key(sKey),dataItem(data), left(lt), right(rt){}

what's wrong with using my constructor this way?

i've been pulling out my hair all night please help me ASAP!!


Non-const references can't be bound to an rvalue, which is what you're trying to do with the argument 9 for the DT &data parameter.

You'll either need to pass in a variable that has the value 9, or you'll need to change the argument (and the dataItem member if it's a reference) to be DT type that gets copied by value into the object. Even if you change the reference to be const to get rid of the compiler error, you'll have an issue with the lifetime of the argument that's passed in if it's a temporary (it won't live past the constructor call, so you'll be left with a dangling reference).

Here's a small example program that demonstrates the problem with binding a const reference in an object to a temporary (an int value returned from rand()). Note that the behavior is undefined, so it might appear to work under some conditions. I tested this program with debug builds on MSVC 2008 and 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();
}

An example run shows:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜