#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
class MyInt
{
friend ostream& operator<<(ostream& cout, MyInt myint);
public:
MyInt()
{
m_num = 0;
}
MyInt operator++(int)//后自增
{
MyInt temp = *this;
m_num++;
return temp;
}
MyInt& operator++()//前自增
{
m_num++;
return *this;
}
private:
int m_num;
};
ostream& operator<<(ostream& cout, MyInt myint)//<<左移运算符重载只能用全局函数,否则不符合需求
{
cout << myint.m_num << endl;//全局函数定义,而后放入需要的类中做友元,可以类外访问友元private属性
return cout;
}
int main()
{
MyInt myint;
int i = 0;
cout << (myint++)++<< endl;//返回0
cout << myint << endl;//返回1
cout << ++(++myint) << endl;//返回3
//cout << (i++)++ << endl;//报错
system("pause");
return 0;
}
C++自增运算符重载注意点:前置递增返回引用,后置递增返回值且不能链式编程
最新推荐文章于 2023-05-19 21:41:02 发布