English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
تحميل العمليات والوظائف الخاصة بـ C++
二元运算符需要两个参数,下面是二元运算符的示例。我们平常使用的加运算符( + )、减运算符( - )、乘运算符( * )和除运算符( / )都属于二元运算符。就像加(+)运算符。
下面的示例演示了如何重载加运算符( + )。类似地,您也可以尝试重载减运算符( - )和除运算符( / )。
#includeusing namespace std; class Box { double length; // 长度 double breadth; // 宽度 double height; // 高度 public: double getVolume(void) { return length * breadth * height; } void setLength( double len ) { length = len; } void setBreadth( double bre ) { breadth = bre; } void setHeight( double hei ) { height = hei; } // 重载 + 运算符,用于把两个 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 Box1; // 声明 Box1,类型为 Box Box Box2; // 声明 Box2,类型为 Box Box Box3; // 声明 Box3,类型为 Box double volume = 0.0; // \u5c06\u4f53\u79ef\u5b58\u5f0a\u5728\u8be5\u53d8\u91cf\u4e2d // Box1\u0020\u7ec6\u8ff0 Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // Box2\u0020\u7ec6\u8ff0 Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // Box1\u0020\u7684\u4f53\u79ef volume = Box1.getVolume(); cout << "Box1\u0020\u7684\u4f53\u79ef\u003a\u0020" << volume << endl; // Box2\u0020\u7684\u4f53\u79ef volume = Box2.getVolume(); cout << "Box2\u0020\u7684\u4f53\u79ef\u003a\u0020" << volume << endl; // إضافة كلا الجسمين للحصول على Box3 Box3 = Box1 + Box2; // حجم Box3 volume = Box3.getVolume(); cout << "Box3 حجمه: " << volume << endl; return 0; }
عندما يتم تجميع وكود التنفيذ أعلاه، سيتم إنتاج النتيجة التالية:
Box1 حجمه: 210 Box2 حجمه: 1560 Box3 حجمه: 5400