C++ Friend class

来源:互联网 发布:程序员培训机构哪个好 编辑:程序博客网 时间:2024/05/16 04:37

Here again, to learn the friend class in C++. And here is a demo for a better understanding.

The demo is mainly to summary the working days till defined date in a year, and using the friend class to realize it.

/*Author: Charles PanDate: 4/14/2014TODO: For the study of friend class in C++*/#include <iostream>using namespace std;class Date;class CustomDate{    private:        int da,yr;    public:        CustomDate(int d = 0,int y =0)        {da  = d; yr = y;}        void Display() const        {std::cout<<std::endl<<yr<<da;}    friend Date;};class Date{    private:        int da,mo,yr;    public:        Date(int m,int d,int y)        {            da = d; mo = m; yr = y;        }        operator CustomDate();};Date::operator CustomDate(){    ///assume this is the working days of this year.    static int dys[]= {23,12,21,22,14,23,12,21,22,14,11,18};    CustomDate cd(0,yr);    ///summay the total work days till defined date of this year.    ///here, in the class date, we access the private memeber "da" of class CustomDate. Coz friend, so we can.    ///This is the kernal part of this code!!!    for(int i=0;i<mo;i++)        cd.da += dys[i];    cd.da+=da;    return cd;}int main(){    Date dt(4,13,2014);    ///convert date to customdate.    CustomDate cd(dt);    cd.Display();    char *tt;    cin >>tt;    return 0;}

More, if we don't want to pre-define the class date, we can do like the following, seems a more better way.

//class Date;  //coment this lineclass CustomDate{    private:        int da,yr;    public:        CustomDate(int d = 0,int y =0)        {da  = d; yr = y;}        void Display() const        {std::cout<<std::endl<<yr<<da;}    friend class Date;  //different with friend Date};


0 0
原创粉丝点击