操作符重载和类的继承
知识点:
1. 操作符重载
一般来讲我们定义在类的里面
格式:返回值 operate
需要重载的操作符(参数){} 例如:void operator++(){}
1.1 加减操作符
class Vector {
public:
Vector(int x, int y) {
this->x = x;
this->y = y;
}
Vector(const Vector &vector) {
this->x = vector.x;
this->y = vector.y;
cout << "拷贝构造函数" << endl;
}
private:
int x;
int y;
public:
void setX(int x) {
this->x = x;
}
void setY(int y) {
this->y = y;
}
int getX() {
return this->x;
}
int getY() {
return this->y;
}
// 重载减号运算符
// 为什么要用引用,为了防止重新创建对象
// const 关键常量,为了防止去修改值
Vector operator-(const Vector &vector) {
int x = this->x - vector.x;
int y = this->y - vector.y;
Vector res(x, y);
return res; // 不建议返回引用
}
Vector operator + (const Vector &vector) {
int x = this->x + vector.x;
int y = this->y + vector.y;
Vector vector(x,y);
return vector;
}
};
int main() {
Vector vector1(2, 3);
Vector vector2(2, 3);
// java 中 string + string;
// char* str = "123" + "456";
//