单目运算符前++与后++的重载
#include "stdafx.h"
#include <iostream>
using namespace std;
//重载前++ 与 后++
//返回对象和引用:优先考虑返回引用
//返回类型加不加const:优先考虑加const类型
//运算符重载 按照基础数据类型的用法
class Complex
{
public:
Complex(float x = 0, float y = 0)
:_x(x), _y(y){}
void dis()
{
cout << "(" << _x << "," << _y << ")" << endl;
}
Complex& operator++(); //前++
const Complex operator++(int); //这个int为哑元 只是为了作区分用的
private:
float _x;
float _y;
};
Complex& Complex::operator++() //前++
{
this->_x++;
this->_y++;
return *this;
}
//const对象不能调用非const成员函数 所以此处加const 可以满足a++++;不成立的条件
const Complex Complex::operator++(int)
{
Complex t(this->_x, this->_y); //先返回一个替身(没进行++运算的) 符合逻辑
this->_x++;
this->_y++;
return t; //此处返回的替身是局部变量,所以返回类型不能&,只能是对象
}
int _tmain(int argc, _TCHAR* argv[])
{
//测试前++的性质
int a = 100;
int b = ++a;
cout << a << " " << b << endl;
++++++++a;
cout << a << endl;
cout << "==================" << endl;
Complex c(1, 2);
Complex c2 = ++++c;
c2.dis();
cout << "==================" << endl;
//测试后++的性质
int p = 100;
int q = a++;
//a++++; 语法不通过
cout << "==================" << endl;
Complex c3(1, 2);
Complex c4 = c3++;
c3.dis();
c4.dis();
return 0;
}