#include<iostream>
using namespace std;
#include <string>
#include<ostream>
class MyInteger {
friend ostream& operator<<(ostream& out, MyInteger m);
public:
MyInteger() {
m_Num = 0;
}
//前置++
MyInteger& operator++() {//因为是直接加,所以要修改返回值 所以用&,不需要传进来变量,
//比如num++ 后面没有变量了
m_Num++;
return *this;//这里返回this this指的是上面的这个num
}
//后置++
// 为什么不是下面的?
// MyInteger operator++(){
// }
// 因为返回值类型不能区分重载
// 所以就用到了下面的int来区分
//
//对于后置++重载,要返回值类型而非引用类型。如果返回引用类型,那么返回的temp就是一个局部对象的引用,局部对象在存储完当前值之后就被释放掉了,其后的返回操作会变为非法操作。
MyInteger operator++(int) {//这里的话int为占位符 把int放里面的编译器就会自动认为是后置++(虽然我不知道为什么)
MyInteger temp = *this;//先记录下未递增的
m_Num++;//递增
return temp;//将记录结果返回
}
private:
int m_Num;
};
ostream& operator<<(ostream& out,MyInteger m) {
out << m.m_Num << endl;
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();
system("pause");
return 0;
}
感觉就是记住。。