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