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 }
复制代码

 

 

 


 元友类:

 

posted @   panda_w  阅读(185)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示