友元函数和友元类代码

#ifndef CHAP_9_H
#define CHAP_9_H

#include "iostream"
using namespace std;

class Date;//需要声明一下
class Test
{
public:
 void show(Date & dt );
};


class Date
{

public:
 Date(int y,int m,int d)
 {
  year=y;
  month=m;
  day=d;
 }
 friend void display(Date &);//定义外部函数为友元函数
 friend class Show;//定义友元类
 friend void  Test::show(Date &);//其他类的成员函数也可以为友元函数
private:
 int year,month,day;
};

void Test::show(Date & dt)//必须放在Date类后面,否则会出现Date未定义的错误
{
 cout<<dt.year<<"year"<<dt.month<<"month"<<dt.day<<"day"<<endl;
}

void display(Date &dt)//一般友元函数,在实际参数中需要指出要访问的对象,友元函数并不是对应类的成员函数,他不带有this指针,因此必须对对象名或对象的引用作为友元函数的参数,并在函数体重实用“.”来访问对象的成员
{
 cout<<dt.year<<"year"<<dt.month<<"month"<<dt.day<<"day"<<endl;
}

 

class Show
{
public :
 void display(Date &);
};
void Show::display(Date &dt)
{
 cout<<dt.year<<"year"<<dt.month<<"month"<<dt.day<<"day"<<endl;
}


#endif

_________________________________________________________________________________________

// chap_9.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "chap_9.h"

int _tmain(int argc, _TCHAR* argv[])
{
 Date d(2010,4,14);
 display(d);
 Test t;
 t.show(d);
 Show s;
 s.display(d);
 return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值