运算符重载
要点:
1. 后置的运算符要带一个整型参数(用来与前置运算符区分开)。
2.后置的返回值不要用引用(否则会因为是局部变量导致返回为一个不存在的值)。
3.再在置中要定义一个临时变量来返回之前的值。
4.在后置运算符中可以使用前置运算符来简化。
代码(内有详解)
#include <iostream>
using namespace std;
class point {
public:
point(int x1 = 0, int y1 = 0) {//构造函数,带默认参数
x = x1;
y = y1;
}
int getx() {
return x;
}
int gety() {
return y;
}
void show() {//用来及时输出值
cout << x << "," << y;
}
point &operator ++();//重载的运算符
point operator ++(int x);
point &operator --();
point operator --(int x);
private:
int x;
int y;
};
point &point:: operator ++() {
this->x++;
this->y++;
return *this;
}
point point::operator ++(int x ) {
point p(*this);//定义一个临时的类来保存加之前的值
++(*this);//利用了重载的前置运算符
return p;
}
point &point:: operator --() {
this->x--;
this->y--;
return *this;
}
point point::operator --(int x ) {
point p(*this);
--(*this);
return p;
}
int main() {
int x, y;
cin >> x >> y;
point p(x, y);
cout << "(" << p.getx() << "," << p.gety() << ")" << endl;
cout << "(" ;
p++.show();
cout << ")" << endl;
cout << "(" ;
(++p).show() ;
cout << ")" << endl;
cout << "(" ;
p--.show() ;
cout << ")" << endl;
cout << "(" ;
(--p).show() ;//前置必须要加小括号
cout << ")" << endl;
return 0;
}