• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
p-boost-q
博客园    首页    新随笔    联系   管理    订阅  订阅
C++友元函数
#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class A
{
    public:
    friend class B;
    private:
        int data;
};
class B
{
    public:
        inline void setValue(int value,A&a)
        {
            a.data = value;
            std::cout << "data : " << a.data << std::endl;
        }
        
};

int main(int argc, char** argv) 
{
    A a;
    B b;
    b.setValue(4,a);
    return 0;
}

上述例子中:

B是A的友元类,这就意味着B的对象和方法可以访问A的任意数据成员和方法,因为友元类可以访问private和protected成员,这就显得相当不安全

#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class A;
class B
{
    public:
    void setValue(int x,A&a);        
};

class A
{
    public:
    friend     void B::setValue(int x,A&a);
    inline void show()
    {
        std::cout << "data : " << data << std::endl;
    }
    private:
        int data;
};
void B::setValue(int x,A&a)
{
    a.data = x;
}

int main(int argc, char** argv) 
{
    A a;
    B b;
    b.setValue(3,a);
    a.show();
    return 0;
}

第一步先声明class A,这是为了在B的成员函数能够接收到A的引用,

第二步在A中声明B的函数setValue为友函数   

第三步在类外定义友元函数

最后在main函数上应用

 

posted on 2019-01-28 23:31  p-boost-q  阅读(187)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3