C++:04.操作符重载和类的继承

知识点:

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";

    // 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值