#include<iostream>
using namespace std;
class Int
{
friend ostream& operator<<(ostream& os,const Int& i);
public:
Int(int i) :m_i(i){}
~Int();
/*const Int operator++(int)
{
Int tmp = *this;
(this->m_i)++;
return tmp;
}*/
Int & operator++()
{
(this->m_i)++;
return *this;
}
private:
int m_i;
};
ostream& operator<<(ostream& os, const Int& i)
{
os <<i.m_i<<'\t'<< endl;
return os;
}
int main()
{
Int a(10);
Int b(15);
++a;
//a++;
cout << a;
return 0;
}
重载操作符++,前置++和后置++的区别的,前置的代码是
Int & operator++()
{
(this->m_i)++;
return *this;
}
可以使用++a而此时不能使用a++,后置代码是
const Int operator++(int)
{
Int tmp = *this;
(this->m_i)++;
return tmp;
}
此时则可以使用a++,自定义类时必须要区分。带参数时则是后置,无参数时则是前置仅仅用于区分,无实际意义。因此在使用时最好使用前置++,无多余的临时变量产生。前置返回引用可以加快运行速率。
1852

被折叠的 条评论
为什么被折叠?



