释放双眼,带上耳机,听听看~!
友元类:在A类中声明B类是它的朋友,B类中定义A类的对象,那么在B类中通过该对象可以实现对A类私有数据的访问
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 1#include<iostream>
2using namespace std;
3
4class A {
5 public :
6 //A将B认作为自己的朋友,B类中的函数可以直访问A类的私有数据
7 friend class B;
8 private:
9 int x;
10};
11
12class B {
13 public:
14 void set(int i);
15 void display();
16 private:
17 A a;
18};
19
20void B::set(int i) {
21 a.x = i;
22}
23
24void B::display()
25{
26 cout << a.x<<endl;
27}
28
29int main() {
30 B b;
31 b.set(3);
32 b.display();
33 return 0;
34}
35
36//注:友元关系不能传递 单向 不能继承
37
38
友元函数:可以在类的外部通过对象使用类的私有数据成员
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35 1#include<iostream>
2#include<cmath>
3using namespace std;
4
5class Point
6{
7 public:
8 Point(int x, int y) :x(x), y(y) {}
9 int getX() { return x; }
10 int getY() { return y; }
11 ~Point();
12 friend float dist(Point p1, Point p2);//友元函数的声明
13
14 private:
15 int x, y;
16};
17
18Point::~Point(){}
19
20//友元函数的实现,可以在类的外部通过对象使用类的私有数据成员
21float dist(Point p1, Point p2) {
22 double x = p1.x - p2.x;
23 double y = p1.y - p2.y;
24 // static_cast<new_type> (expression) 强制类型转换
25 return static_cast<double>(sqrt(x*x + y*y));
26}
27
28int main()
29{
30 Point p1(1, 2), p2(4, 6);
31 cout<<dist(p1,p2)<<endl;
32 return 0;
33}
34
35