单目运算符-作为成员重载
#include "stdafx.h"
#include <iostream>
using namespace std;
//单目运算符重载
//M# #M ++a a++
//operator#(L); 作友元
//L.operator#(); 作成员
class Complex
{
public:
Complex(float x = 0, float y = 0)
:_x(x), _y(y){}
void dis()
{
cout << "(" << _x << "," << _y << ")" << endl;
}
//返回类型为const是因为不能修改 例如-n=30; 不能用30将-n的值修改
//而函数为const函数是因为 负号- 允许再次调用 例如-(-n);
//而-n的返回类型为const类型 const类型数据只能调用const类型函数
//所以此函数也需要是const类型的
const Complex operator-() const
{
//Complex c;
//c._x = -this->_x;
//c._y = -this->_y;
//return c;
//Complex c(-this->_x, -this->_y);
//return c;
return Complex(-this->_x, -this->_y);//直接返回构造后的对象
}
private:
float _x;
float _y;
};
int _tmain(int argc, _TCHAR* argv[])
{
int n = 5;
cout << n << endl;
cout << -n << endl;
cout << -(-n) << endl;
//-n=30; 编译不能通过
cout << "================================" << endl;
Complex c(1, 1);
Complex t = -(-c); // c.operator-().operator-();
c.dis();
t.dis();
Complex m = (2, 2);
//-c = m;
return 0;
}