C++友元函数1
#include<iostream>
using namespace std;
class book
{
public:
book(){}
book(char* a, double p);
friend void display(book &b);
private:
double price;
char * title;
};
book::book(char* a, double p)
{
title = a;
price = p;
}
void display(book &b)
{
cout<<"The price of "<<b.title<<" is $"<<b.price<<endl;
}
int main()
{
book Alice("Alice in Wonderland",29.9);
display(Alice);
book Harry("Harry potter", 49.9);
display(Harry);
return 0;
}

friend void display(book &b);
友元函数2
#include<iostream>
using namespace std;
class time;
class date
{
public:
date(int y,int m,int d);
void display(time &t);
private:
int year;
int month;
int day;
};
class time
{
public:
time(int s,int m,int h);
friend void date::display(time & t);
private:
int second;
int minute;
int hour;
};
time::time(int s,int m,int h)
{
second = s;
minute = m;
hour = h;
}
date::date(int y,int m,int d)
{
year = y;
month = m;
day = d;
}
void date::display(time &t)
{
cout<<"The time is year month:"<<endl;
cout<<year<<"/"<<month<<"/"<<day<<" " << endl;
cout<<"The time is t.hour t.minute:"<<endl;
cout<<t.hour<<":"<<t.minute<<":"<<t.second<<endl;
}
int main()
{
date d(2015,1,16);
time t(20,2,30);
d.display(t);
return 0;
}

友元类
#include<iostream>
using namespace std;
class time;
class date
{
public:
date(int y,int m,int d);
void display(time &t);
private:
int year;
int month;
int day;
};
class time
{
public:
time(int s,int m,int h);
friend void date::display(time & t);
private:
int second;
int minute;
int hour;
};
time::time(int s,int m,int h)
{
second = s;
minute = m;
hour = h;
}
date::date(int y,int m,int d)
{
year = y;
month = m;
day = d;
}
void date::display(time &t)
{
cout<<"The time is:"<<endl;
cout<<year<<"/"<<month<<"/"<<day<<" ";
cout<<t.hour<<":"<<t.minute<<":"<<t.second<<endl;
}
int main()
{
date d(2015,1,16);
time t(20,2,30);
d.display(t);
return 0;
}
