gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:21:53 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com