///友元
///友元有利于数据共享,但是破坏了类的封装性
#include <iostream>
using namespace std;
class Date; ///对Date类提前声明
class Time {
public:
Time (int h,int m,int s):hour(h),minute(m),sec(s) {};
void display(Date &d);
private:
int hour;
int minute;
int sec;
};
class Date {
public:
Date(int m,int d,int y):month(m),day(d),year(y) {}
///声明Time中display函数为本类的友元成员函数,可以访问本类的私有成员
friend void Time::display(Date &d);
private:
int month;
int day;
int year;
};
void Time::display(Date &d) {
cout<<d.month<<" "<<d.day<<" "<<d.year<<endl;
cout<<hour<<" "<<minute<<" "<<sec<<endl;
}
int main() {
Time t(10,13,56);
Date d(12,25,2016);
t.display(d);
return 0;
}