zoukankan      html  css  js  c++  java
  • C++之友元函数和友元类

    通过friend关键字,我们可以将不属于当前类的一个函数在当前类中加以声明,该函数便可以成为当前类的友元函数。

    #include<iostream>
    using namespace std;

    class book
    {
    public:
        book()
        {
           cout <<this->price << endl;  //这里是没有赋值的成员变量就使用,这是不可取的
           cout << this->title << endl;

        }
        book(char* a, double p);
        friend void display(book &b);
    private:
        double price;
        char * title;
    };

    book::book(char* a, double p)
    {
        title = a;
        price = p;
    }

    void display(book &b)
    {
        cout<<"The price of "<<b.title<<" is $"<<b.price<<endl;
    }

    int main()
    {
        book Hello;
        display(Hello);
        book Alice("Alice in Wonderland",29.9);
        display(Alice);
        book Harry("Harry potter", 49.9);
        display(Harry);

        return 0;
    }

    // result :6.95314e-310

     在我们知道能用友元函数能访问类中的私有变量,还有一点要记住,没有初始化的成员变量不能使用,会使程序崩溃。

    在本例中,display是一个顶层函数,在book类中,我们借助friend关键字将其声明为友元函数,结果,在display函数体内,我们就能访问private属性的title和price成员变量。这就是友元函数的作用。友元函数可以访问这个类中的私有成员。如果这个display函数不是book类的友元函数,则在函数体中还必须调用public属性的成员函数。在此例中需要注意的是友元函数的形参是类对象的引用,同时在访问私有成员变量时必须要加上对象名。

    除了顶层函数可以被定义为友元函数之外,其它类的成员函数同样可以声明为本类的友元函数,如例2所示。

    例 2

    #include<iostream>
    using namespace std;

    class time;

    class date
    {
    public:
        date(int y,int m,int d);
        void display(time &t);
    private:
        int year;
        int month;
        int day;
    };

    class time
    {
    public:
        time(int s,int m,int h);
        friend void date::display(time & t);
    private:
        int second;
        int minute;
        int hour;
    };

    time::time(int s,int m,int h)
    {
        second = s;
        minute = m;
        hour = h;
    }

    date::date(int y,int m,int d)
    {
        year = y;
        month = m;
        day = d;
    }

    void date::display(time &t)
    {
        cout<<"The time is:"<<endl;
        cout<<year<<"/"<<month<<"/"<<day<<" ";
        cout<<t.hour<<":"<<t.minute<<":"<<t.second<<endl;
    }

    int main()
    {
        date d(2015,1,16);
        time t(20,2,30);
        d.display(t);
        return 0;
    }

     





  • 相关阅读:
    AndoridSQLite数据库开发基础教程(9)
    AndoridSQLite数据库开发基础教程(8)
    AndoridSQLite数据库开发基础教程(7)
    AndoridSQLite数据库开发基础教程(6)
    AndoridSQLite数据库开发基础教程(5)
    当music-list向上滑动的时候,设置layer层,随其滚动,覆盖图片,往下滚动时候,图片随着展现出来
    开发song-list组件;
    封装一个音乐列表music-list基础组件,可以共用,哪个需要的时候就是哪个props相应的值
    获取并封装歌手歌曲的数据
    使用vuex保存singer每个歌星的基本信息
  • 原文地址:https://www.cnblogs.com/wanghuixi/p/7092500.html
Copyright © 2011-2022 走看看