C++中的友元机制

    C++中的友元机制(friend),可以不通过调用成员函数便能直接访问类的私有数据。友元可以是函数(友元函数),也可以是类(友元类)。

    一、友元函数

        1.声明:在类体内,在函数类型前要加关键字friend;

        2.定义:在类体外,格式与普通函数一样;

        3.特点:(1)友元函数为非成员函数,调用上与普通函数一样;

                        (2)可直接访问该类中私有成员。

    二、友元类

        当声明一个类为另一个类的友元时,友元类中的所有成员函数都是另一个类的友元函数。


    通过下面的代码例子,就会更明白了。


   
   
  1. #include <iostream>
  2. using namespace std;
  3. class X
  4. {
  5. public:
  6. friend class Y; //类Y是类X的友元类
  7. void set(int i)
  8. {
  9. x = i;
  10. }
  11. void display()
  12. {
  13. cout << "x=" << x << ";" << "y:" << y <<endl;
  14. }
  15. private:
  16. int x;
  17. static int y;
  18. };
  19. class Y
  20. {
  21. public:
  22. Y(int i,int j);
  23. void display();
  24. private:
  25. X a; //数据成员为类X的对象
  26. };
  27. int X::y = 10;
  28. Y::Y(int i,int j)
  29. {
  30. a.x = i;
  31. X::y = j;
  32. }
  33. void Y::display()
  34. {
  35. cout << "x=" << a.x << "," << "y=" << X::y <<endl;
  36. }
  37. int main()
  38. {
  39. X b;
  40. b.set(5);
  41. b.display();
  42. Y c(6,9);
  43. c.display();
  44. b.display();
  45. return 0;
  46. }

    运行结果为:

            


    注意:友元机制的作用主要是为了提高程序的运行效率和方便编程。但同时友元破坏了类的封装性,所以使用时慎重。

        <div class="person-messagebox">
            <div class="left-message"><a href="https://blog.csdn.net/buknow">
                <img src="https://profile.csdnimg.cn/D/E/4/3_buknow" class="avatar_pic" username="buknow">
            </a></div>
            <div class="middle-message">
                                    <div class="title"><span class="tit "><a href="https://blog.csdn.net/buknow" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;,&quot;ab&quot;:&quot;new&quot;}" target="_blank">n大橘为重n</a></span>
                    <!-- 等级,level -->
                                            <img class="identity-icon" src="https://csdnimg.cn/identity/blog5.png">                                            </div>
                <div class="text"><span>原创文章 89</span><span>获赞 224</span><span>访问量 15万+</span></div>
            </div>
                            <div class="right-message">
                                        <a class="btn btn-sm  bt-button personal-watch" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;,&quot;ab&quot;:&quot;new&quot;}">关注</a>
                                                            <a href="https://im.csdn.net/im/main.html?userName=buknow" target="_blank" class="btn btn-sm bt-button personal-letter">私信
                    </a>
                                </div>
                        </div>
                    
    </div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值