将普通函数声明为友元函数
#include<iostream>
using namespace std;
class time
{public:
time(int,int,int);
friend void display(time &);
private:
int hour;
int minute;
int sec;
};
time::time(int h,int m,int s)
{ hour = h;
minute = m;
sec = s;
}
void display(time&t)
{ cout << t.hour << ":" << t.minute << ":" << t.sec << endl;}
int main()
{time t1(14,30,30);
display(t1);
return 0;
}
程序运行结果
14:30:30
Process returned 0 (0x0) execution time : 0.010 s
Press any key to continue.
友元成员函数
- 有一个日期(
date
)类的对象和一个时间(time
)类的对象,均已指定了内容,要求一次输出其中的日期和时间
#include<iostream>
using namespace std;
class date;
class time
{public:
time(int,int,int);
void display(date &);
private:
int hour;
int minute;
int sec;
};
class date
{public:
date(int,int,int);
friend void time::display(date &);
private:
int month;
int day;
int year;
};
time::time(int h,int m, int s)
{hour = h;
minute = m;
sec = s;
}
void time::display(date &d)
{cout << d.month << "/" <<d.day << "/" << d.year << endl;
cout << hour << ":" << minute << ":" << sec << endl;
}
date::date(int m,int d,int y)
{month = m;
day = d;
year = y;
}
int main()
{time t1(13,51,56);
date d1(5,31,2021);
t1.display(d1);
return 0;
}
程序运行结果
5/31/2021
13:51:56
Process returned 0 (0x0) execution time : 0.037 s
Press any key to continue.
练习
- 将上例程序中的display函数不放在time类中,而作为类外的普通函数,然后分别在time和date类中将display声明为友元函数。在主函数中调用display函数,display函数分别引用time和date两个类的对象的私有数据,输出年月日和时分秒。
#include<iostream>
using namespace std;
class date;
class time
{public:
time(int,int,int);
friend void display(time &);
private:
int hour;
int minute;
int sec;
};
class date
{public:
date(int,int,int);
friend void display(date &);
private:
int month;
int day;
int year;
};
time::time(int h,int m, int s)
{hour = h;
minute = m;
sec = s;
}
void display(date &d)
{cout << d.month << "/" <<d.day << "/" << d.year << endl; }
void display(time &t)
{cout << t.hour << ":" << t.minute << ":" << t.sec << endl;
}
date::date(int m,int d,int y)
{month = m;
day = d;
year = y;
}
int main()
{time t1(13,51,56);
date d1(5,31,2021);
display(t1);
display(d1);
return 0;
}
程序运行结果
13:51:56
5/31/2021
Process returned 0 (0x0) execution time : 0.021 s
Press any key to continue.