zoukankan      html  css  js  c++  java
  • 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函数上应用

  • 相关阅读:
    多个表单项的动态校验
    js遍历循坏二维数组,显示天气情况
    纯css3 实现的焦点图
    实现元素水平和垂直居中的问题
    简易商品购物车
    用jquery的animate动画做成的左侧菜单伸缩
    MongoDB聚合
    NoSQL介绍
    MongoDB索引
    数据库索引简介
  • 原文地址:https://www.cnblogs.com/boost/p/10332238.html
Copyright © 2011-2022 走看看