C++遞減運算子過載
阿新 • • 發佈:2021-02-04
技術標籤:C++面向物件
#include<iostream>
#include<string>
using namespace std;
//通過全域性函式過載
class MyInteger {
friend ostream&operator<<(ostream &cout, MyInteger m);
public:
MyInteger() {
m_Num = 0;
}
//過載前置--運算子
MyInteger& operator--() {
m_Num--;
return *this;
}
//過載後置++運算子
MyInteger operator--(int) {
MyInteger temp = *this;
m_Num--;
return temp;
}
private:
int m_Num;
};
//還需要過載左移運算子
ostream & operator<<(ostream &cout, MyInteger m) {
cout << m.m_Num;
return cout;
}
void test01() {
MyInteger myint;
cout << --myint << endl;
cout << myint <<endl;
}
void test02() {
MyInteger myint;
cout << myint-- << endl;
cout << myint << endl;
}
int main() {
test01();
test02();
return 0;
}