以非成員函數方式重載運算符
/*** 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; }
運算結果:
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
?
當兩個對象相加時是沒有順序要求的,但是要重載+讓其與一個數字相加有順序要求,可以通過加一個友元函數使另一個順序的輸出合法。
/*** 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) //對象和數相加 {return A(a+b); }A operator+ (const int b, A obj) // 友元函數調用第二個重載+的成員函數,相當于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; //可以調換順序,相當于a3=a1.operator+(a2); a3.display();a4 = a1 + m; //加了一個友元函數可調換順序 a4.display();a5 = m + a1;a5.display();return 0; }
運算結果:
exbot@ubuntu:~/wangqinghe/C++/20190808$ ./overfrined
1
2
3
2
2