C++ Friend class

本文通过一个示例展示了如何在C++中使用友元类来实现特定功能。该示例涉及日期类与自定义日期类之间的交互,利用友元特性访问私有成员并计算指定日期前的工作日总数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值