C++_练习—元友三友

元友三友


 元友函数:

  全局函数作为友元函数:

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class info {
 6 public:
 7     void init(int a);
 8     friend void yuan_fun(info a); // 注意元友函数的参数!!
 9 
10 private:
11     int age;
12 };
13 
14 void info::init(int a) {
15     age = a;
16 }
17 
18 //元友函数
19 void yuan_fun(info a) {
20     int num = a.age;
21     cout << num << endl;
22 }
23  
24 int main(void) {
25 
26     info info1;      //类定义一个对象
27     info1.init(6);   //初始化对象
28     yuan_fun(info1); //元友打印
29 
30     system("pause");
31 
32     return 0;
33 }

  成员函数作为友元函数:

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class info;  // 前向声明,是种不完全型声明,只需提供类名(⽆无需提供类实现)即可,仅可⽤用于声明指针和引⽤
 6             // 错误找了好久
 7 
 8 class text {
 9 public:
10     void text_fun(info a);
11 };
12 
13 class info {
14 public:
15     void info_fun(int ini);
16     friend void text::text_fun(info a);
17 private:
18     int info_age;
19 };
20 
21 
22 void info::info_fun(int ini) {
23     info_age = ini;
24 }
25 
26 void text::text_fun(info a) {
27     int num = a.info_age;
28     cout << num << endl;
29 }
30 
31 int main(void)
32 {
33     info info1;
34     info1.info_fun(6);      //初始对象
35 
36     text text1;
37     text1.text_fun(info1);  //成员函数元友打印初始
38 
39     system("pause");
40 
41     return 0;
42 }

 元友类:

Stay hungry, stay foolish 待续。。。
原文地址:https://www.cnblogs.com/panda-w/p/11356958.html