操作符重载问题

来源:百度知道 编辑:UC知道 时间:2024/05/18 03:17:52
#include <iostream>
using namespace std;
class Counter
{
public:
Counter();
~Counter(){}
int GetItsVal() const {return ItsVal;}
void SetItsVal(int x) {ItsVal=x;}
const Counter& operator++ ();
const Counter operator++(int);
private:
int ItsVal;
};
Counter::Counter():ItsVal(0){}

const Counter& Counter::operator++()
{
++ItsVal;
return *this;
}

const Counter Counter::operator++(int)
{
Counter temp(*this);
++ItsVal;
return temp;
}

int main()
{
Counter i;
cout<<"the value of i is"<<i.GetItsVal()<<endl;

i++;

cout<<"the value of i is"<<i.GetItsVal()<<endl;

++i;

cout<<"the value of i is"<<i.GetItsVal()<<endl;

Counter a = ++i;

cout<<"the valu

this是指向调用这个成员函数的对象的指针 那么return *this就是返回这个对象 又因为函数的返回类型是引用 所以最终返回调用该成员函数的对象的引用
++i;
时候被调用
const Counter Counter::operator++(int)
{
Counter temp(*this);
++ItsVal;
return temp;
}
Counter temp(*this); 是多余的啊!

const Counter& Counter::operator++()
是前置操作符,当然在++i;的时候调用呀
返回*this的意思是返回当前正在使用的对象,即i

而const Counter Counter::operator++(int)
是后置操作符,当然在i++;的时候调用

The operator '++' has two overload method:
operator++(void) means ++i, there's no any type parameters here.

operator++(int) means i++, Here int is just a signal, its only use is to tell compiler that here is a "i++" operator, it has no other use, we don't need to give it a type argument.

"Return this*" returns the Counter object by reference. Because it's a ++i like operator, in the class, it firstly increases
ItsVal by 1, then return the same Counter object which is the original