运算符的重载使得我们可以更加方便的使用常见的运算符进行操作。
重载运算符的函数格式如下:
1
| operatorop(argement-list)
|
接下来的例子中,我们将定义一个Time类,并通过重载运算符+和<<来实现时间的加法和输出显示,其中会使用友元函数(friend)
time.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #ifndef TIME_H #define TIME_H #include <iostream> class Time{ private: int minute; int hour; public: Time(); Time(int h=0,int m=0); Time operator+(const Time & t)const; friend std::ostream & operator<<(std::ostream & os, const Time & t); } #end if
|
time.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #include"time.h" Time::Time(){ hour=minute=0; } Time::Time(int h,int m){ hour=h; minute=m; } Time operator+(const Time & t)const{ Time sum; sum.minute=minute+t.minute; sum.hour=hour+t.hour; sum.minute%=60; return sum; }
std::ostream & operator<<(std::ostream & os, const Time &t){ os<<t.hour<<"hours,"<<t.minute<<"minutes"; return os; }
|
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #include<iostream> #include"time.h" int main(){ using std::cout; using std::endl; Time aida(3,35); Time tosca(2,48); cout<<"aida:"<<aida<<";tosca:"<<tosca<<endl; cout<<"aida+tosca="<<aida+tosca<<endl; return 0; }
aida:3 hours,35 minutes tosca:2 hours,48 minutes aida+tosca=4 hours,11 minutes
|