简体   繁体   English

C ++错误:没有匹配的函数来调用“”

[英]C++ Error : No Matching Function for Call to “ ”

am new to the community.Was practicing Operator Overloading using '+' operator when I got this error. 我是社区的新手。收到此错误时,正在使用“ +”运算符练习运算符重载。

C:\Users\User\Documents\Saahil\h23.cpp  In member function 'Time 
Time::operator+(const Time&)':
10  8   C:\Users\User\Documents\Saahil\h23.cpp  [Error] no matching function 
for call to 'Time::Time()'
10  8   C:\Users\User\Documents\Saahil\h23.cpp  [Note] candidates are:
8   2   C:\Users\User\Documents\Saahil\h23.cpp  [Note] Time::Time(int, int)
8   2   C:\Users\User\Documents\Saahil\h23.cpp  [Note] candidate expects 2 
arguments, 0 provided
4   7   C:\Users\User\Documents\Saahil\h23.cpp  [Note] Time::Time(const 
Time&)
4   7   C:\Users\User\Documents\Saahil\h23.cpp  [Note] candidate expects 1 
argument, 0 provided

CODE: 码:

#include<iostream>
using namespace std;

class Time{
   public:
    int min;
    int s;
Time(int min, int s){ this->min=min;this->s = s; }
Time operator +(Time const &obj){
    Time total_time;
    total_time.min = min + obj.min;
    total_time.s = s+ obj.s;
    return total_time;
}
void print(){  cout<<"The time now is : "<<min<<":"<<s; }
};




/*Constructor*/ 


int main()
{

//cout<<"Enter the time intervals to be added :  "<<endl; cin>>min1>>s1;
//cout<<"Enter second time interval :  "; cin>>min2>>s2;
//Time t1(min1,s1) , t2(min2,s2);
Time t1(11 ,23), t2(23,29);
Time t3 = t1+t2;
t3.print();

}

I have tried removing the this keyword but that seemed to just aggravate the problem. 我曾尝试删除此关键字,但这似乎只会加剧问题。 PLease help! 请帮忙!

In your operator function you do 在操作员功能中,您可以

Time total_time;

That defines a new Time object and default construct it. 定义一个新的Time对象并默认构造它。 But you don't have a Time default constructor, so the compiler complains about that. 但是您没有Time默认构造函数,因此编译器对此表示抱怨。

The solution is to either use the parameterised constructor you already have, or to create a default constructor. 解决方案是使用已有的参数化构造函数,或者创建默认构造函数。

The line 线

Time total_time;

is not right. 是不正确的。 You don't have a default constructor. 您没有默认的构造函数。

One solution: 一种解决方案:

Time operator +(Time const &obj)
{
    return Time(this->min + obj.min,  this->s + obj.s);
}

You should also make the member function a const member function. 您还应该使成员函数成为const成员函数。

Time operator +(Time const &obj) const
{
    return Time(this->min + obj.min,  this->s + obj.s);
}

That will allow you to use: 那将允许您使用:

Time t1(11, 23);
Time t2(23, 29);
Time t3(5, 8);

Time t4 = t1 + t2 + t3;

Your operator + tries to default-construct a Time , but it has no default constructor. 您的运算符+试图默认构造一个Time ,但是它没有默认构造函数。

Do this instead (and add const while you're at it): 改为这样做(并在使用时添加const ):

Time operator +(Time const &obj) const {
    return Time(min + obj.min, s + obj.s);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM