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函数上应用

  • 相关阅读:
    uva 11995 I Can Guess the Data Structure!
    poj 1981 Circle and Points
    hdoj 2149 Public Sale
    hdoj 2188 悼念512汶川大地震遇难同胞——选拔志愿者
    hdoj 1846 Brave Game
    vue 细节注意
    meta标签设置不缓存
    -webkit-overflow-scrolling
    ios上表单默认样式
    vue-cli项目上传到github预览问题
  • 原文地址:https://www.cnblogs.com/boost/p/10332238.html
Copyright © 2011-2022 走看看