C++中运算符+重载出错
//Time.h
#ifndef TIME_H
#define TIME_H
#include<iostream>
using namespace std;
class Time
{
public:
Time(int H=0,int M=0,int S=0);
void SetTime(int H,int M,int S);
Time operator+(const Time &t, int n);
friend ostream & operator<<(ostream &out,const Time &t);
private:
int h,m,s;
};
#endif
//Time.cpp
#include<iostream>
#include"Time.h"
using namespace std;
Time::Time(int H,int M,int S):h(H),m(M),s(S){}
void Time::SetTime(int H,int M,int S)
{
h=H,m=M,s=S;
}
Time Time::operator+(const Time &t, int n)
{
Time temp(t);
int y=n+s+60*(m+60*h);
temp.s=y%60;
temp.m=y/60%60;
temp.h=y/3600;
return temp;
}
ostream & operator<<(ostream &out,const Time &t)
{
out<<t.h<<":"<<t.m<<"."<<t.s;
return out;
}
//Test.cpp
#include<iostream>
#include"Time.h"
using namespace std;
int main()
{
Time t1,t2;
t1.SetTime(23,10,29);
t2.SetTime(10,4,23);
cout<<t1+3;
return 0;
}
我的理解是重载operator+,相当于timeObj1+timeObj2,如果增加了参数int n,这个表达式没办法展开,也就形成不了操作符号重载。
类内重载操作符直接写第二个操作数就行
Time operator+( int n);
//运行时是这么调用的
t1.operator+(3);
//按你原来的写法会缺变量
t1.operator+((const Time&)3, (int)???)
//类外重载需要按你原来的写法,调用方式是
operator+(t1, 3);
那如果是1+a和a+1运算不同,需要分别声明呢??