C++笔记7(重载运算符代码)

本文通过一个具体的C++项目实例,展示了如何实现运算符重载,包括加法、减法、前置和后置自增操作及等于比较等。通过对Box类的操作,详细解释了重载的具体实现方式。

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


前言

最近学习了重载运算符的相关知识。用法和定义其他大佬已经做了详细的解释,本人不再过多赘述。这篇博客主要用来展示关于重载运算符的一个小小小项目。


头文件

#pragma once
#ifndef cpp_second_hpp
#define cpp_second_hpp

#include <stdio.h>
#include <iostream>
using namespace std;

class Box{
public:
    double getVolume(void);
    
    void setLength(double len);
    
    void setBreadth(double bre);
    
    void setHeight(double hei);
    
    //重载运算符,把两个Box对象相加
    Box();
    Box(const Box& box);
    
    Box operator=(const Box& box);
    
    bool operator==(const Box& box);
    
    Box operator-(const Box& box);
    
    Box operator++();
    
    Box operator++(int);
    
private:
    double length;
    double breath;
    double height;
};
#endif

cpp文件

#include "cpp_second.hpp"
#include<iostream>
using namespace std;

double Box::getVolume(void) {
    return length * height * breath;
}

void Box::setHeight(double hei) {
    height = hei;
}

void Box::setBreadth(double bre) {
    breath = bre;
}

void Box::setLength(double len) {
    length = len;
}

Box::Box() = default;
Box::Box(const Box& box) {
    this->height = box.height;
    this->breath = box.breath;
    this->length = box.length;
}

Box Box::operator=(const Box& b) {
    length = b.length;
    height = b.height;
    breath = b.breath;
    return *this;
}

bool Box::operator==(const Box& b) {
    if(length == b.length && breath == b.breath && height == b.height){
        return true;
    }
    return false;
}

Box Box::operator-(const Box& b){
    length = length - b.length;
    height = height - b.height;
    breath = breath - b.breath;
    return *this;
}

Box Box::operator++() {
    ++length;
    ++height;
    ++breath;
    return *this;
}

Box Box::operator++(int) {
    Box temp = *this;
    length++;
    height++;
    breath++;
    return temp;
}
int main() {
    Box box1;
    box1.setLength(8);
    box1.setHeight(5);
    box1.setBreadth(3);

    Box box2;
    box2 = box1;

    Box box3;
    box3.setLength(1);
    box3.setHeight(1);
    box3.setBreadth(1);

    box2 - box3;
    box1++;
    ++box1;
    if (box1 == box2) {
        cout << box2.getVolume() << endl;
    }
    cout << box1.getVolume() << endl;
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

du__kefeng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值