日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

二元运算符重载

發(fā)布時間:2023/11/30 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 二元运算符重载 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

以非成員函數(shù)方式重載運(yùn)算符

/*** overtwo.cpp ***/ #include<iostream> using namespace std;class Box {public:Box(double l = 2.0,double b = 2.0,double h = 2.0){length = l;breadth = b;height = h;}double getVolume(){return length*breadth*height;}private:double length;double breadth;double height;friend Box operator+(const Box& a,const Box& b); };Box operator+(const Box& a,const Box& b) {Box box;box.length = a.length+b.length;box.breadth = a.breadth+b.breadth;box.height = a.height + b.height;return box; }int main() {Box box1(3.3,1.2,1.5);Box box2(8.5,6.0,2.0);Box box3;double volume = 0.0;volume = box1.getVolume();cout << "Volume of box1 : " << volume << endl;volume = box2.getVolume();cout << "Volume of box2 : " << volume << endl;box3 = box1 + box2;volume = box3.getVolume();cout << "Volume of box3 : " << volume << endl;return 0; }

運(yùn)算結(jié)果:

exbot@ubuntu:~/wangqinghe/C++/20190808$ g++ overtwo.cpp -o overtwo

exbot@ubuntu:~/wangqinghe/C++/20190808$ ./overtwo

Volume of box1 : 5.94

Volume of box2 : 102

Volume of box3 : 297.36

?

當(dāng)兩個對象相加時是沒有順序要求的,但是要重載+讓其與一個數(shù)字相加有順序要求,可以通過加一個友元函數(shù)使另一個順序的輸出合法。

/*** overfriend.cpp ***/ #include<iostream> using namespace std;class A {private:int a;public:A();A(int n);A operator+(const A &obj);A operator+(const int b);friend A operator+(const int b,A obj);void display(); };A::A() {a = 0; }A::A(int n) {a = n; }A A::operator +(const A& obj) //重載+號,用于對象相加 {return this->a+obj.a; }A A::operator+(const int b) //對象和數(shù)相加 {return A(a+b); }A operator+ (const int b, A obj) // 友元函數(shù)調(diào)用第二個重載+的成員函數(shù),相當(dāng)于obj.operator(b) {return obj+b; }void A::display() {cout << a << endl; }int main() {A a1(1);A a2(2);A a3,a4,a5;a1.display();a2.display();int m = 1;a3 = a1 + a2; //可以調(diào)換順序,相當(dāng)于a3=a1.operator+(a2); a3.display();a4 = a1 + m; //加了一個友元函數(shù)可調(diào)換順序 a4.display();a5 = m + a1;a5.display();return 0; }

運(yùn)算結(jié)果:

exbot@ubuntu:~/wangqinghe/C++/20190808$ ./overfrined

1

2

3

2

2

轉(zhuǎn)載于:https://www.cnblogs.com/wanghao-boke/p/11319659.html

總結(jié)

以上是生活随笔為你收集整理的二元运算符重载的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。