前言
最近学习了重载运算符的相关知识。用法和定义其他大佬已经做了详细的解释,本人不再过多赘述。这篇博客主要用来展示关于重载运算符的一个小小小项目。
头文件
#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;
}