您的位置:首页 > 编程语言 > C语言/C++

C++ Friend class

2014-04-14 23:09 465 查看
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 Pan
Date: 4/14/2014
TODO: 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 line
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 class Date;  //different with friend Date
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: