#include <iostream>
using namespace std;
//重载运算符
//自定义整型
class MyInteger {
public:
friend ostream& operator<<(ostream& cout, const MyInteger& myint);
MyInteger() {
m_Num = 0;
}
//重载前置++运算符
MyInteger& operator++() {
//先进行++的运算
m_Num++;
//再返回对象本身
return *this;
}
//重载后置++运算符
//void operator++(int) int代表占位参数,可以用于区分前置和后置运递增
MyInteger operator++(int)
{
//先 记录当时的结果
MyInteger temp=*this;
//后 递增
m_Num++;
//最后 返回之前记录的结果
return temp;
}
private:
int m_Num;
};
//重载输出流运算符
ostream& operator<<(ostream& cout,const MyInteger& myint) {
cout << myint.m_Num;
return cout;
}
void test01() {
MyInteger myint;
cout << ++myint << endl;
}
void test02() {
MyInteger myint;
cout << myint++ << endl;
cout<<myint<<endl;
}
int main() {
//test01();
test02();
return 0;
}
《c++》递增运算符重载
最新推荐文章于 2024-08-21 18:16:36 发布