自增运算符重载
约 0 个字 55 行代码 预计阅读时间 1 分钟
#include <iostream>
using namespace std;
class MyInteger{
friend ostream & operator << (ostream & out ,MyInteger myInteger);
private:
int num;
public:
MyInteger(){
num = 0;
}
//前置++
MyInteger& operator++(){
this->num++;
return *this;
}
//后置++
MyInteger operator++(int){
MyInteger temp = * this;//记录当前本身的值,
// 然后让本身的值加1,但是返回的是以前的值,达到先返回后++;
num++;
return temp;
}
};
ostream & operator << (ostream & out ,MyInteger myInteger){
out << myInteger.num;
return out;
}
//前置++ 先++ 再返回
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;
}