标签:opera 操作 r++ return 重载 区分 后缀 names 而不是
递增运算符(++)和递减运算符(--)是C++语言中两个重要的一元运算符。
/*** addMyself.cpp ***/ #include<iostream> using namespace std; class Time { private: int hours; int minutes; public: Time() { hours = 0; minutes = 0; } Time(int h,int m) { hours = h; minutes = m; } void displayTime() { cout << "H: " << hours << " M" << minutes << endl; } //重载前缀递增运算符 Time operator++() { ++minutes; if(minutes >= 60) { ++hours; minutes -= 60; } return Time(hours,minutes); } //重载后缀递增运算符 Time operator++(int) { Time T(hours,minutes); ++minutes; if(minutes >= 60) { ++hours; minutes -= 60; } return T; } }; int main() { Time T1(11,59),T2(10,40); ++T1; T1.displayTime(); ++T1; T1.displayTime(); T2++; T2.displayTime(); T2++; T2.displayTime(); return 0; }
运行结果:
exbot@ubuntu:~/wangqinghe/C++/20190808$ g++ addMyself.cpp -o addMyself
exbot@ubuntu:~/wangqinghe/C++/20190808$ ./addMyself
H: 12 M0
H: 12 M1
H: 10 M41
H: 10 M42
注意:int在括号是为了向编译器说明这是一个后缀形式,而不是表示整数。
前缀形式重载调用Check operator++(),后缀形式重载调用operator++(int)
/*** addOver.cpp ***/ #include<iostream> using namespace std; class Check { private: int i; public: Check():i(0){}; Check operator++ () { Check temp; temp.i = ++i; return temp; } Check operator ++ (int) { Check temp; temp.i = i++; return temp; } void Display() { cout << "i = " << i << endl; } }; int main() { Check obj1,obj; obj.Display(); obj1.Display(); obj1 = ++ obj; obj.Display(); obj1.Display(); obj1 = obj++; obj.Display(); obj1.Display(); return 0; }
运行结果:
exbot@ubuntu:~/wangqinghe/C++/20190808$ ./addOver
i = 0
i = 0
i = 1
i = 1
i = 2
i = 1
递减和递增运算符重载:
标签:opera 操作 r++ return 重载 区分 后缀 names 而不是
原文地址:https://www.cnblogs.com/wanghao-boke/p/11326019.html