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