1普通函数声明友元函数
#include<iostream>
using namespace std;
class Timer
{
public:
Timer(int,int,int);
friend void display(Timer& t);
private:
int h;
int m;
int s;
};
Timer::Timer(int a,int b,int c)
{
h=a;
m=b;
s=c;
}
void display(Timer& t)
{
cout<<t.h<<endl;
cout<<t.m<<endl;
cout<<t.s<<endl;
}
int main()
{
Timer timer(12,34,56);
display(timer);
return 0;
}
2成员函数声明友元函数
#include<iostream>
using namespace std;
class Date;
class Time
{
public:
Time(int,int,int);
void display(Date& d);
private:
int hour;
int min;
int sec;
};
class Date
{
public:
Date(int,int,int);
friend void Time::display(Date& d);
private:
int year;
int mon;
int day;
};
Time::Time(int a,int b,int c)
{
hour=a;
min=b;
sec=c;
}
Date::Date(int a,int b,int c)
{
year=a;
mon=b;
day=c;
}
void Time::display(Date& d)
{
cout<<d.year<<" "<<d.mon<<d.day<<endl;
cout<<hour<<min<<sec<<endl;
}
int main()
{
Time t1(11,22,33);
Date d1(44,55,66);
t1.display(d1);
return 0;
}
3友元类
#include<iostream>
using namespace std;
class Date;
class Time
{
public:
Time(int,int,int);
void display(Date& d);
private:
int hour;
int min;
int sec;
};
class Date
{
public:
Date(int,int,int);
friend class Time;
private:
int year;
int mon;
int day;
};
Time::Time(int a,int b,int c)
{
hour=a;
min=b;
sec=c;
}
Date::Date(int a,int b,int c)
{
year=a;
mon=b;
day=c;
}
void Time::display(Date& d)
{
cout<<d.year<<" "<<d.mon<<d.day<<endl;
cout<<hour<<min<<sec<<endl;
}
int main()
{
Time t1(11,22,33);
Date d1(44,55,66);
t1.display(d1);
return 0;
}