[搬运]C++ 运算符重载(简单易懂)

AquaRio

2019-06-24 16:38:29

Personal

# C++ 运算符重载: >您可以重定义或重载大部分 C++ 内置的运算符。这样,您就能使用自定义类型的运算符。 重载的运算符是带有特殊名称的函数,函数名是由关键字 operator 和其后要重载的运算符符号构成的。 与其他函数一样,重载运算符有一个返回类型和一个参数列表。 > 重载 + 运算符 , 把两个 Box 相加 Box operator+(const Box b) ------------ ## demo: ```cpp h = 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++ 支持重载的运算符: ![C++ 支持重载的运算符:](https://img-blog.csdn.net/20180907142335170?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjgzNzAyNA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) ## 不支持重载的运算符: ![不支持重载的运算符:](https://img-blog.csdn.net/20180907142354740?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjgzNzAyNA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)