作用: 通过重载递增运算符,实现自己的整型数据
#include<iostream>
using namespace std;
//重载递增运算符
//自定义整型
class MyInteger
{
friend ostream& operator<<(ostream& cout, const MyInteger& myint);
public:
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 test1()
{
MyInteger myint;
cout << ++(++myint) << endl;//2
cout << myint << endl;//2 如果返回值而不是返回引用则为1,因为返回的是一个临时的对象,而非常量引用不能绑定到临时对象上
}
void test2()
{
MyInteger myint;
cout << myint++ << endl;//0 需要将左移重载的第二个参数改为常量引用,友元函数也是(老师课堂代码无const)
cout << myint << endl;//1
/*test2函数中执行 cout << myint++ << endl; 时,
myint++ 表达式调用的是后置递增运算符,它返回一个临时的 MyInteger 对象。
但是由于operator<< 定义为接受一个非常量引用 MyInteger & ,
而非常量引用不能绑定到临时对象上,因此编译器报错。*/
}
int main()
{
//test1();
test2();
return 0;
}
//前后置递减只需将++变为--
总结:前置递增返回引用,后置递增返回值