c++ 运算符重载(简单易懂)

本文详细介绍了C++中运算符重载的概念与应用,通过Box类的实例,展示了如何重载+和-运算符来实现自定义类型的数据运算。适合初学者理解运算符重载的基本原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c++ 运算符重载:

您可以重定义或重载大部分 C++ 内置的运算符。这样,您就能使用自定义类型的运算符。

重载的运算符是带有特殊名称的函数,函数名是由关键字 operator 和其后要重载的运算符符号构成的。

与其他函数一样,重载运算符有一个返回类型和一个参数列表。
    //重载 + 运算符 , 把两个 Box 相加
    Box operator+(const Box b) 

demo:

#include <iostream>
class Box {

public:
    //求面积
    double getVolume() {
        return length * width * height;
    }

    void setLength(double len) {
        this->length = len;
    }

    void setWidth(double width) {
        this->width = width;
    }

    void setHeight(double height) {
        this->height = height;
    }
    //重载 + 运算符 , 把两个 Box 相加
    Box operator+(const Box b) {

        Box box_;
        box_.length = this->length + b.length;
        box_.height = this->height + b.height;
        box_.width = this->width + b.width;

        return box_;
    }
    //重载 - 运算符 , 把两个 Box 相减 
    Box operator-(const Box b) {

        Box box_;
        box_.length = this->length - b.length;
        box_.width = this->width - b.width;
        box_.height = this->height - b.height;

        return box_;
    }

private:

    double length;
    double width;
    double height;

};


int main()
{
    Box a;
    a.setHeight(5);
    a.setWidth(5);
    a.setLength(2);

    std::cout << "a. volume:" << a.getVolume() << std::endl;

    Box b;
    b.setHeight(5);
    b.setWidth(5);
    b.setLength(5);

    std::cout << "b. volume:" << b.getVolume() << std::endl;

    Box c;

    c = a + b;

    std::cout << "c. volume:" << c.getVolume() << std::endl;



    Box d;

    d =  b  - a;

    std::cout << "d. volume:" << d.getVolume() << std::endl;

    system("pause");

    return 0;
}

这里写图片描述

c++ 支持重载的运算符:

这里写图片描述

不支持重载的运算符:

这里写图片描述

    98年菜鸡一枚,请大佬们多多照顾!
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值