c++ 运算符重载(简单易懂)
生活随笔
收集整理的這篇文章主要介紹了
c++ 运算符重载(简单易懂)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
c++ 運算符重載:
您可以重定義或重載大部分 C++ 內置的運算符。這樣,您就能使用自定義類型的運算符。重載的運算符是帶有特殊名稱的函數(shù),函數(shù)名是由關鍵字 operator 和其后要重載的運算符符號構成的。與其他函數(shù)一樣,重載運算符有一個返回類型和一個參數(shù)列表。 //重載 + 運算符 , 把兩個 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年菜雞一枚,請大佬們多多照顧!總結
以上是生活随笔為你收集整理的c++ 运算符重载(简单易懂)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Flask 和 requests 搭建一
- 下一篇: win7下安装MQTT Paho客户端