009_linuxC++之_友元函数

(一)定义:友元函数是指某些虽然不是成员却能够访问类的所有成员的函数。类授予它的友元特别的访问权。通常同一个开发者会出于技术和非技术的原因,控制类的友元和成员函数(否则当你想更新你的类时,还要征得其它部分的拥有者的同意)。

(二)使用非友元函数将两个对象中的变量进行相加

 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 }
View Code

(三)使用友元函数进行两个对象中变量的相加

 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 }
View Code

猜你喜欢

转载自www.cnblogs.com/luxiaoguogege/p/9690674.html