友元

关于友元这个讲的比较好:http://wuyuans.com/2012/09/cpp-operator-overload/

我现在觉得友元就是当时C++之父 Bjarne Stroustrup为了给程序员一个偷懒的方式,而引入了友元这种东西。

我这次想说的运算符重载是有两个方式的,一种是友元的方式,另一种是成员函数的方式,这两种方式的区别是函数的参数个数不同例如:

 1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 class Complex
 6 {
 7 private:
 8     double x;
 9     double y;
10 public:
11     friend Complex operator - (Complex &a, Complex &b);
12     Complex(double x, double y);
13     Complex();
14     Complex operator + (Complex &a);
15     void show();
16 };
17 
18 Complex::Complex()
19 {
20 
21 }
22 
23 Complex::Complex(double x, double y)
24 {
25     this->x = x;
26     this->y = y;
27 }
28 
29 Complex Complex::operator+(Complex &a)
30 {
31     return Complex(x+a.x,y+a.y);
32 }
33 
34 void Complex::show()
35 {
36     cout << "x = " << x << endl;
37     cout << "y = " << y << endl;
38 }
39 
40 Complex operator - (Complex &a, Complex &b)
41 {
42     return Complex(a.x-b.x, a.y-b.y);
43 }
44 
45 int main()
46 {
47     Complex com1(1, 2), com2(1, 3), com3;
48     com3 = com1 + com2;
49     com3.show();
50     com3 = com1 - com2;
51     com3.show();
52     return 0;
53 }

看!两种不同的实现方式。这应该算是设计模式里的东西吧》》》

原文地址:https://www.cnblogs.com/chaiwentao/p/4557225.html