zoukankan      html  css  js  c++  java
  • 友元——友元可以访问与其有好友关系的类中的私有成员。 友元包括友元函数和友元类。

    简介:友元可以访问与其有好友关系的类中的私有成员。
         友元包括友元函数和友元类。

    【1】将普通函数声明为友元函数

    #include<iostream>
    using namespace std;
    
    class Time
    {
            public:
                    Time(int,int,int);
                    friend void display(Time &);//定义友元函数
            private:
                    int hour;
                    int minute;
                    int sec;
    };
    
    Time::Time(int h,int m,int s)
    {
            hour = h;
            minute = m;
            sec = s;
    }
    
    void display(Time&t)
    {
            cout<<t.hour<<":"<<t.minute<<":"<<t.sec<<endl;
    }
    /*由于声明了display Timedisplay是Time
      friend函数,所以Time display函数可以引用Time
      display  Time中的私有成员 hour,minute,sec。
      但注意在引用这些私有数据成员
      hour,minute,sec时,必须加上对象名,不能写成
      cout<<hour<<′′:′′<<minute<<′′:′′<<sec<<endl;  
    */
    int main()
    {
            Time t1(10,13,56);
            display(t1);
            return 0;
    }
    View Code

      

    【2】一个函数(包括普通函数和成员函数)可以被多个
      类声明为“朋友”,这样就可以引用多个类中的私有
      数据

    #include<iostream>
    using namespace std;
    class Date;
    class Time
    {
            public:
                    Time(int,int,int);
                    void display(Date &);//display 是成员函数,形式参数date类的
            private:
                    int hour;
                    int minute;
                    int sec;
    
    };
    
    class Date
    {
            public:
                    Date(int,int,int);
                    friend void Time::display(Date&);//声明time中的display函数为友元函数
            private:
                    int month;
                    int day;
                    int year;
    
    };
    
    Time::Time(int h,int m,int s)
    {
            hour = h;
            minute = m;
            sec = s;
    }
    
    void Time::display(Date &d)
    {
            cout<<d.month<<"/"<<d.day<<"/"<<d.year<<endl;//引用date类的私有数据
            cout<<hour<<":"<<minute<<":"<<sec<<endl;//引用本类中的私有数据
    
    }
    
    Date::Date(int m,int d,int y)
    {
            month = m;
            day = d;
            year = y;
    }
    int main()
    {
            Time t1(10,13,56);
            Date d1(12,25,2004);
            t1.display(d1);
            return 0;
    }
    View Code

    友元比较好的博客推荐:

  • 相关阅读:
    npm WARN saveError ENOENT: no such file or directory的解决方法
    简单的webpack打包案例
    JS中用encodeURIComponent编码,后台JAVA解码
    说 Redis
    let the cat out of the bag
    简述C# volatile 关键字
    螃蟹怎么分公母?是用冷水上锅还是热水蒸呢?
    Mysql截取字符串 更新字段的部分内容
    Ajax 获取数据attr后获取不到
    如何限制域名访问?白名单机制
  • 原文地址:https://www.cnblogs.com/fengdashen/p/3889744.html
Copyright © 2011-2022 走看看