小记一次操作符,方便日后回顾。
#include<ostream>
#include <iostream>
using namespace std;
class MyInt
{
//全局友元函数
friend ostream& operator<<(ostream& o, MyInt myint);
int num;
public:
MyInt() :num(0){};
//++前置
MyInt& operator++()
{
num++;
return *this;
}
//--前置
MyInt& operator--()
{
num--;
return *this;
}
//后置++
//后置不能引用是因为变量在栈区,函数用完即销毁,故值传递
//此处int为占位符,下同
MyInt operator++(int)
{
MyInt temp = *this;
num++;
return temp;
}
//后置--
MyInt operator--(int)
{
MyInt temp = *this;
num--;
return temp;
}
};
/*
*注意!
*必须采用值传递以兼容前置和后置操作,因为后置操作的匿名变量会立即销毁
*为了安全和性能尽量少用后置操作
*/
ostream& operator<<(ostream &o, MyInt myint)
{
return o<<myint.num;
}
int main()
{
MyInt m_int;
cout<< --m_int<<endl;//-1
cout<< ++m_int << endl;//0
cout << ++(++m_int) << endl;//2 链式编程
cout << --(--m_int) << endl;//0 链式编程
cout << m_int++ << endl;//0
cout << m_int-- << endl;//1
cout << "现在的m_int:" << m_int << endl;
//现在的m_int:0
cout << (m_int++)++ << endl;
//1 因为我们只是第一次对num操作了,第二次对一个匿名变量操作了++
cout << (m_int++, m_int++) << endl;
//2 因为逗号运算符,每次都对m_int操作
cout << "现在的m_int:" << m_int << endl;//3
return 0;
}
因此,尽量少用后置++,除非必要!谢谢观看!