简体   繁体   中英

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. But you don't have a Time default constructor, so the compiler complains about that.

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.

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.

Do this instead (and add const while you're at it):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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