创建一个类class MyInteger
class MyInteger
{
public:
MyInteger()
{
m_Num = 0;
}
//前置++
MyInteger& operator++()
{
m_Num++;//先++
return *this;//再返回
}
//后置++
MyInteger operator++(int)
{
MyInteger temp = *this; //记录当前本身的值,然后让本身的值加1,但是返回的是以前的值,达到先返回后++;
m_Num++;
return temp;
}
public:
int m_Num;
};
编译器区分前置++和后置++的方法是在后置++里加int,只能加int
重载<<运算符,只能用全局函数
ostream& operator<<(ostream& out, MyInteger myint)
{
out << myint.m_Num;
return out;
}
调试函数
//前置++ 先++ 再返回
void test01()
{
MyInteger myInt;
cout << ++myInt << endl;
cout << myInt << endl;
}
//后置++ 先返回 再++
void test02()
{
MyInteger myInt;
cout << myInt++ << endl;
cout << myInt << endl;
}
main函数顺序调用test01()和test02(),结果如下