(一)定義:友元函數是指某些雖然不是類成員卻可以訪問類的全部成員的函數。類授予它的友元特別的訪問權。一般同一個開發者會出於技術和非技術的緣由,控制類的友元和成員函數(不然當你想更新你的類時,還要徵得其它部分的擁有者的贊成)。html
(二)使用非友元函數將兩個對象中的變量進行相加ios
1 #include <iostream> 2 #include <string.h> 3 #include <unistd.h> 4 5 using namespace std; 6 7 class Point { 8 private: 9 int x; 10 int y; 11 12 public: 13 Point() {} 14 Point(int x, int y) : x(x), y(y) {} 15 16 int getX(){ return x; } 17 int getY(){ return y; } 18 void setX(int x){ this->x = x; } 19 void setY(int y){ this->y = y; } 20 void printInfo() 21 { 22 cout<<"("<<x<<", "<<y<<")"<<endl; 23 } 24 }; 25 26 Point add(Point &p1, Point &p2) 27 { 28 Point n; 29 n.setX(p1.getX()+p2.getX()); 30 n.setY(p1.getY()+p2.getY()); 31 return n; 32 } 33 34 int main(int argc, char **argv) 35 { 36 Point p1(1, 2); 37 Point p2(2, 3); 38 39 Point sum = add(p1, p2); 40 sum.printInfo(); 41 42 return 0; 43 }
(三)使用友元函數進行兩個對象中變量的相加ide
1 #include <iostream> 2 #include <string.h> 3 #include <unistd.h> 4 5 using namespace std; 6 7 class Point { 8 private: 9 int x; 10 int y; 11 12 public: 13 Point() {} 14 Point(int x, int y) : x(x), y(y) {} 15 16 int getX(){ return x; } 17 int getY(){ return y; } 18 void setX(int x){ this->x = x; } 19 void setY(int y){ this->y = y; } 20 void printInfo() 21 { 22 cout<<"("<<x<<", "<<y<<")"<<endl; 23 } 24 friend Point add(Point &p1, Point &p2); 25 }; 26 27 Point add(Point &p1, Point &p2) 28 { 29 Point n; 30 n.x = p1.x+p2.x; 31 n.y = p1.y+p2.y; 32 return n; 33 } 34 35 int main(int argc, char **argv) 36 { 37 Point p1(1, 2); 38 Point p2(2, 3); 39 40 Point sum = add(p1, p2); 41 sum.printInfo(); 42 43 return 0; 44 }