本文共 2291 字,大约阅读时间需要 7 分钟。
c++函数重载:可以将一个函数名用于不同功能的函数。从而处理不同的对象。对于运算符,同样也有这样的用途,即对同一个标志符的运算符,可以运用到不同的功能中去。
首先引入:运算符重载,在C语言中甚至都有运算符重载的例子:比如*可以表示指针,也可以表示为乘法。用在不同的环境下,发挥的用途是不同的。
在类中,可以将运算符重载成高级形式,比如将两个类进行相加:
类声明:
1 # ifndef MYTIME0_H_ 2 # define MYTIME0_H_ 3 4 class Time 5 { 6 private: 7 int hours; 8 int minutes; 9 public:10 Time();11 Time(int h, int m = 0);12 void AddMin(int m);13 void AddHr(int h);14 void Reset(int h = 0, int m = 0);15 Time operator+(const Time &t) const;16 void Show() const;17 18 };19 # endif
类接口函数定义:
1 # include "iostream" 2 # include "mytime0.h" 3 4 Time::Time() 5 { 6 hours = minutes = 0; 7 } 8 9 Time::Time(int h, int m)10 {11 hours = h;12 minutes = m;13 }14 15 void Time::AddMin(int m)16 {17 minutes += m;18 hours = minutes / 60;19 minutes = minutes % 60;20 }21 22 void Time::AddHr(int h)23 {24 hours = hours + h;25 }26 27 void Time::Reset(int h, int m)28 {29 hours = h;30 minutes = m;31 }32 33 Time Time::operator+(const Time &t)const34 {35 Time sum;36 sum.minutes = minutes + t.minutes;37 sum.hours = hours + t.hours + sum.minutes / 60;38 sum.minutes = sum.minutes % 60;39 return sum;40 }41 42 void Time::Show()const43 {44 using std::cout;45 using std::endl;46 std::cout << hours << "hours," << minutes << "minutes" << endl;47 }
类调用:
1 # include "iostream" 2 # include"mytime0.h" 3 4 int main() 5 { 6 using std::cout; 7 using std::endl; 8 Time planning; 9 Time coding(2, 40);10 Time fixing(5, 55);11 Time total;12 13 cout << "planninf time =";14 planning.Show();15 cout << endl;16 17 cout << "coding time =";18 coding.Show();19 cout << endl;20 21 cout << "fixing time =";22 fixing.Show();23 cout << endl;24 25 total = coding+fixing;26 cout << "total time =";27 total.Show();28 cout << endl;29 30 system("pause");31 return 0;32 33 }
关注第25行,我们可以像对待基本类型一样对待我们定义的类,对其进行相加运算。
可能我们会问这样一个问题:如果说将两个int型数据相加得到的是int 型数据,那么将类相加的意义又是什么呢?
其实将类相加的本质只是:用+替换了某一个方法的使用方式,并不是真正字面理解的将两个对象加起来!!!很明显,这里的+调用的原型是Time Time::operator+(const Time &t)const
我们可以认为operator+替代了原来的sum这一名字。因此实际当使用coding+fixing时,使用的是coding.operator+(fixing).因此,当我们看到将类相加时,第一反应应该是:调用了类中的某个方法,而该方法的功能是完成了某种加法运算,而不是思考将类相加时什么含义!!!
参考:C++入门之深入剖析——类深入
转载地址:http://gbpfz.baihongyu.com/