C++ 二元运算符重载
二元运算符需要两个参数
常用的二元运算符包括
加运算符 ( + ) 减运算符 ( - ) 乘运算符 ( * ) 除运算符 ( / )
下面我们就来写一个范例尝试重载加运算符 ( + )
/** * file: main.cpp * author: 简单教程(www.twle.cn) * * Copyright © 2015-2065 www.twle.cn. All rights reserved. */ #include <iostream> class Box { double length; // 长度 double breadth; // 宽度 double height; // 高度 public: Box () { length = 0.0; breadth = 0.0; height = 0.0; } Box (double a, double b ,double c ) { length = a; breadth = b; height = c; } double getVolume(void) { return length * breadth * height; } // 重载 + 运算符,用于把两个 Box 对象相加 Box operator+(const Box& b) { Box box; box.length = this->length + b.length; box.breadth = this->breadth + b.breadth; box.height = this->height + b.height; return box; } }; int main( ) { Box b1(3.0, 4.0, 5.0); Box b2(13.0, 18.0, 32.0); Box b3; std::cout << "Volume of b1 : " << b1.getVolume() << "\n"; std:: cout << "Volume of b2 : " << b2.getVolume() << "\n"; // 把两个对象相加,得到 Box3 b3 = b1 + b2; // Box3 的体积 std::cout << "Volume of b3 : " << b3.getVolume() << "\n"; return 0; }
使用 g++ main.cpp && ./a.out
命令编译运行以上范例,输出结果如下:
Volume of b1 : 60 Volume of b2 : 7488 Volume of b3 : 13024