【问题标题】:C++ error: no matching function for call toC++ 错误:没有匹配的调用函数
【发布时间】:2014-04-08 18:04:12
【问题描述】:

这是我得到的错误: "没有匹配的函数调用 'MemberForTest::MemberForTest'..."

代码如下:

#include "Base.h"
#include "Date.h"

class MemberForTest: public tp::Base
{
public:
    MemberForTest(std::string& name, std::string& firstname,
            Date& birthday, std::string& telephone);

};




class Member
{
public:
    Member() :
        perso("Hall", "roger", (12,12,1990), "(999) 444-4545")
    {
    };

    MemberForTest perso;
};

Base 是一个抽象类。我的老师使用相同的方法来获取基类构造函数,他不需要创建函数 (MemberForTest::MemberForTest)。即使我创建了函数,错误仍然存​​在。你能帮帮我吗?

另外,我可能必须传递一个对象日期 (Date date(12,12,1990)) 而不是 (12,12,1990) 作为参数。我该怎么做?

【问题讨论】:

  • Date(12, 12, 1990),尽管尚不清楚(并且高度怀疑)为什么构造函数通过引用接收所有内容。
  • 没有从 int 1990 到类 Date 的隐式转换?令人震惊...
  • 更好地让构造函数接收常量引用而不是可变引用

标签: c++ class parameters constructor abstract


【解决方案1】:

你用来初始化Date的表达式,即

(12,12,1990)

是一个逗号表达式,其计算结果为 int(具体来说,1990,逗号分隔数字链中的最后一个数字)。该错误表明intDate 不兼容。

修改您的代码以构造一个Date 对象。不幸的是,您不能内联,因为MemberForTest 构造函数通过非常量引用获取Date 参数。如果您将构造函数更改为通过常量引用获取参数,就像这样

MemberForTest(const std::string& name, const std::string& firstname,
        const Date& birthday, const std::string& telephone);

你应该能够做到这一点:

Member() :
    perso("Hall", "roger", Date(12,12,1990), "(999) 444-4545")
{
};

【讨论】:

  • 字符串也引用了。
  • @jrok 啊,你说得对,string refs 也应该是const。谢谢!
【解决方案2】:

当一个参数被声明为对非常量的引用时,例如std::string& name,它的参数需要是一个左值(一个命名对象)。您正在传递字符串文字 - 这些是字符数组,而不是 std::string,需要进行转换。转换的结果是一个临时对象,一个右值。语言规则规定这些不能传递给对非常量的引用。

您需要声明构造函数以采用const std::string&(因为您不会更改参数),或者首先创建std::string 类型的对象:

void foo(std::string& s);
std::string str;
foo(str);

另外,(12,12,1990) 不会创建临时的 Date 对象(为此,您需要使用函数样式转换 - Date(12,12,1990))。这是一个带括号的表达式,使用 comma operator,计算左侧操作数,丢弃它们,并返回最右侧的操作数(整数文字 1990)。

string参数一样,你需要带const Date&

【讨论】:

    猜你喜欢
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    相关资源
    最近更新 更多