友元成员函数

 1 //  friend 不仅 可以是一般函数 , 而且可以是另一个类的成员函数
 2 //  本例中除了介绍到 有关友元函数的 简单应用外  还将用到 类的 提前应用 声明
 3 #include<iostream>
 4 using namespace std;
 5 class date;                       //   对 date类 进行  提前引用声明
 6 class time     //  声明  time 类
 7 {
 8 public:
 9     time(int ,int ,int );   // 声明构造函数
10     void display(date&); //  display 是成员函数 , 形参 是 date 类 对象的  引用
11 private:
12     int hour;
13     int minute;
14     int sec;
15 };
16 class date       //   声明 date 类
17 {
18 public:
19     date(int,int,int);   //声明 构造函数
20     friend void time::display(date&);  //声明 time类 中的 display 函数 为 本类的 友元函数
21 private:
22     int month;
23     int day;
24     int year;
25 };
26 time::time(int h,int m,int s)
27 {
28     hour=h;
29     minute=m;
30     sec=s;
31 }
32 void time::display(date&d)
33 {
34     cout<<d.month<<"/"<<minute<<d.day<<"/"<<d.year<<endl;
35     cout<<hour<<":"<<minute<<":"<<sec<<endl;
36 }
37 date::date(int m,int d,int y)   // 类 date的 构造函数
38 {
39     month=m;
40     day=d;
41     year=y;
42 }
43 int main()
44 {
45     time t1(10,13,56);  //  定义 time类 对象t1
46     date d1(12,25,2004);
47     t1.display(d1);
48     return 0;
49 }
原文地址:https://www.cnblogs.com/A-FM/p/5236134.html