C++加法运算符的重载(operator)

1.重载加法运算符

为什么要重载加法运算符?

因为C++提供的加法运算符只能满足基本数据类型间的加法,如果我想让俩个相同的类的对象进行加法的话会报错

image-20231218154406227

所以为了能让俩个相同类的对象进行加法,我们要把这个过程封装到一个函数里面,只不过要多加一个关键字operator而已,让编译器一下子就找到,这个是重载运算符的函数

作用:实现俩个自定义运算符相加

成员函数实现运算符重载

#include <iostream>
​
using namespace std;
​
class Box {
    int length;
    int width;
    int height;
public:
    Box() {
        length = 0;
        width = 0;
        height = 0;
    }
    Box(int length,int width,int height) {
        this->length = length;
        this->width = width;
        this->height = height;
    }
    Box(const Box& other) {
        length = other.length;
        width = other.width;
        height = other.height;
    }
    //成员函数重载加法运算符
    Box operator+(const Box& other) {
        Box p;
        p.length = this->length + other.length;
        p.width = this->width + other.width; 
        p.height = this->height + other.height;
        return p;
    }
};
int main() {
    Box a(1,2,3);
    Box b(2, 3, 4);
    Box c = a + b;//直接调用
    Box d;
    d = a.operator+(b);//调用重载运算符的函数
    return 0;
}

全局函数实现运算符的重载

#include <iostream>
​
using namespace std;
​
class Box {
    int length;
    int width;
    int height;
    friend Box operator+(const Box& other1, const Box& other2);
    friend Box operator+(const Box& other1, int val);
public:
    Box() {
        length = 0;
        width = 0;
        height = 0;
    }
    Box(int length,int width,int height) {
        this->length = length;
        this->width = width;
        this->height = height;
    }
    Box(const Box& other) {
        length = other.length;
        width = other.width;
        height = other.height;
    }
};
//全局函数重载加法运算符
Box operator+(const Box& other1,const Box& other2) {//不调用成员函数是无法访问私有的成员变量的,需要设置为友元,告诉编译器,我这个重载运算符的函数是你这个类的好朋友,都哥们,能f
    Box p;
    p.length = other1.length + other2.length;
    p.width = other1.width + other2.width;
    p.height = other1.height + other2.height;
    return p;
}
Box operator+(const Box& other1,int val) {
    Box p;
    p.length = other1.length + val;
    p.width = other1.width + val;
    p.height = other1.height + val;
    return p;
}
int main() {
    Box a(1,2,3);
    Box b(2, 3, 4);
    Box c = a + b;
    Box d;
    d=operator+(a,b);
    return 0;
}
  • 15
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值