美文网首页
c++ 友元

c++ 友元

作者: 杀破魂 | 来源:发表于2020-01-24 08:50 被阅读0次

    在c++中,通过关键字friend声明为友元。友元可以范围与其有好友关系的类中私有成员。友元包括友元函数和友元类。

    友元函数

    如果在本类以外的其他地方定义一个函数(这个函数可以是不属于任何类的非成员函数,也可以是其他类的成员函数),在对本类进行声明时在类体重用friend对改函数进行声明,此函数就称为友元函数

    普通函数声明为友元函数

    
    #include<iostream>
    using namespace std;
     
    class Time
    {
    public:
        Time(int, int, int);
            friend void display(Time &);//声明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;
    }
     
    int main(void)
    {
        Time t1(10, 13, 56);
        display(t1);
        return 0;
    }
    

    display是一个在类外定义的且未用类Time的限定函数,它是非成员函数,不属于任何类。

    友元成员函数

    
    #include<iostream>
    using namespace std;
     
    class Date;//对Date类的提前引用声明
    class Time
    {
    public:
        Time(int, int, int);
        void display(Date &);
    private:
        int hour;
        int sec;
        int minute;
    };
     
    class Date
    {
    public:
        Date(int, int, int);
        friend void Time::display(Date &);//声明Time类中display函数为本类的友元成员函数
    private:
        int mouth;
        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.mouth << "/" << d.day << "/" << d.year << endl;
        cout << hour << ":" << minute << ":" << sec << endl;
    }
     
    Date::Date(int m, int d, int y)
    {
        mouth = m;
        day = d;
        year = y;
    }
     
    int main(void)
    {
        Time t1(10, 13, 56);
        Date d1(4, 15, 2019);
        t1.display(d1);
        return 0;
    }
    

    一个函数可以被多个类声明为友元,这样就尅应用多个类中的私有数据。

    友元类

    将类B声明为另一个类A的友元,这是B类就是A类的友元类。友元类B中的所有函数都是A类的友元函数,可以访问A类中的所有成员。
    在A类的定义体走咯个声明B类为其友元类:
    friend B;
    声明友元类的一般格式为
    friend 类名;

    注意:

    • 友元关系是单向的,不是双向的。声明了B类是A类的友元类,不等于A类是B类的友元类,A类中的成员函数不能访问B类中的私有数据。
    • 友元关系不能传递。如果 B类是A类的友元类,C类是B类的友元类,不等于C类是A类的友元类。

    友元类可以访问其他类中的私有成员,可以说这是对封装原则的一个小的破坏。

    相关文章

      网友评论

          本文标题:c++ 友元

          本文链接:https://www.haomeiwen.com/subject/luutthtx.html