调用 [类] 没有匹配函数

No matching function for call to [class]

本文关键字:函数 调用      更新时间:2023-10-16

所以,我有一些我正在定义的类,它给了我错误:

#include <iostream>
using namespace std;;
//void makepayment(int amount, string name, Date date);
//void listpayments();
class Date;
class Date {
  public:
    int month;
    int day;
    int year;
    Date(int month, int day, int year) {
      this->month = month;
      this->day = day;
      this->year = year;
    }
};
class Payment {
  public:
    int amount;
    string name;
    Date date;
    Payment(int amount, string name, Date date) {
      this->amount = amount;
      this->name = name;
      this->date = date;
    }
};
int main() {
cout <<
"|~~~~~~~~~~~~~~~~~~~~~~~~| n" <<
"|   WELCOME TO THE       | n" <<
"|   WESSLES BANK         | n" <<
"|   MANAGEMENT SYSTEM!   | n" <<
"|~~~~~~~~~~~~~~~~~~~~~~~~| n";
for(;;) {
}
return 0;  
}

错误是:

foo.cpp: In constructor ‘Payment::Payment(int, std::string, Date)’:
foo.cpp:26:49: error: no matching function for call to ‘Date::Date()’
foo.cpp:26:49: note: candidates are:
foo.cpp:14:5: note: Date::Date(int, int, int)
foo.cpp:14:5: note:   candidate expects 3 arguments, 0 provided
foo.cpp:9:7: note: Date::Date(const Date&)
foo.cpp:9:7: note:   candidate expects 1 argument, 0 provided

我不知道出了什么问题!"呼叫没有匹配功能"是什么意思?

对不起,如果这是一个菜鸟问题...我刚开始 c++。

这是因为您尝试复制对象,但没有提供默认构造函数。

this->date = date;

您应该做的是初始化初始值设定项列表中的所有内容。您也没有理由不通过引用传递其中一些参数。

Payment(int amount, const string& name, const Date& date)
    : amount(amount)
    , name(name)
    , date(date)
    {}

您的Date课也是如此。这将使用编译器生成的复制构造函数。请注意,如果您的类包含的 POD 类型多于POD类型,则可能需要实现自己的复制构造函数。

因为你有

Date date;

在您的 Payment 类中,您必须有一个不带参数的 Date 构造函数,即 Date::D ate(),您没有指定该参数。

付款类有一个日期子项。Payment 构造函数首先尝试使用默认构造函数实例化 Date 子项,然后为此子项分配一个新值。问题是 Date 子项没有默认构造函数 Date::D ate()。为 Date 类指定默认构造函数,或更改付款构造函数语法,如下所示:

Payment::Payment(int amount_, string name_, Date date_) : amount(amount_),
    name(name_), date(date_)
{
}

编辑:美学家打败了我