负号重载
#include <iostream>
using namespace std;
//负号返回的是临时变量,不能作为左值,同时存在 -(-a)=a的情况,所以函数要为常函数,第一次调用负号重载函数返回的是const,常对象不能调用非常函数所以 要将负号重载函数定义为常函数
class points
{
private:
int x;
int y;
public:
points (int, int);
void display();
const points operator-() const;
};
points::points(int x, int y) : x(x), y(y){};
void points::display()
{
cout << "x: " << this->x << "y: " << this->y;
};
const points points::operator-() const
{
return points(-this->x,-this->y);
}
int main()
{
points p1(11,22);
points p2=-p1;
points p3=-(-p1);//第一次调用负号重载函数返回的是const,常对象不能调用非常函数所以 要将负号重载函数定义为常函数
p2.display();
p3.display();
}