【问题标题】:No matching function for call to [class]调用 [class] 没有匹配的函数
【发布时间】:2013-09-24 01:03:55
【问题描述】:

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

#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++。

【问题讨论】:

    标签: c++ class compiler-errors


    【解决方案1】:

    这是因为你试图复制一个对象,但没有提供默认构造函数。

    this->date = date;
    

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

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

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

    【讨论】:

    • 好的。谢谢!我主要是一个java程序员。刚开始c++ tody :P.
    • 没问题。玩得开心 C++!
    【解决方案2】:

    因为你有

    Date date;
    

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

    【讨论】:

      【解决方案3】:

      Payment 类有一个 Date 子类。 Payment 构造函数首先尝试使用默认构造函数实例化 Date 子项,然后再为该子项分配一个新值。问题是 Date 子节点没有默认构造函数 Date::Date()。要么给 Date 类一个默认构造函数,要么改变 Payment 构造函数语法如下:

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

      编辑:Esthete 打败了我

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-16
        • 1970-01-01
        • 2014-11-29
        • 1970-01-01
        • 2017-10-16
        • 1970-01-01
        • 2021-09-21
        • 2016-11-23
        相关资源
        最近更新 更多