練習要求:設計 Date 和 Time 類,編寫全局函數 display(Date&, Time&) 輸出日期時間。要求 display 為普通函數,但在兩個類中均聲明為 friend,以訪問私有數據。
#include <iostream>
using namespace std;
class Time; // 前向聲明
class Date {
int year, month, day;
public:
Date(int y, int m, int d) : year(y), month(m), day(d) {}
friend void display(const Date&, const Time&); // 友元聲明
};
class Time {
int hour, minute, second;
public:
Time(int h, int m, int s) : hour(h), minute(m), second(s) {}
friend void display(const Date&, const Time&); // 友元聲明
};
void display(const Date& d, const Time& t) {
cout << d.year << '/' << d.month << '/' << d.day << endl;
cout << t.hour << ':' << t.minute << ':' << t.second << endl;
}
int main() {
int y, m, d, h, mi, s;
cin >> y >> m >> d >> h >> mi >> s;
Date dt(y, m, d);
Time tm(h, mi, s);
display(dt, tm);
return 0;
}
friend 打破封裝,讓非成員函數訪問 private 成員;display 需在兩個類中分別聲明為友元;const 引用,避免拷貝且保護數據不被修改。