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

1.重载加法运算符

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

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

C++加法运算符的重载(operator)_第1张图片

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

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

成员函数实现运算符重载

#include 
​
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 
​
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;
}

你可能感兴趣的:(c++,算法,前端)