通过Date类的display (Time &t)函数引用Time类对象的私有数据,输出时:分:秒
时间: 2023-11-28 07:49:19 浏览: 40
可以通过在Date类中定义 `display` 函数来实现输出时分秒的功能,代码如下:
```c++
#include<iostream>
using namespace std;
class Time {
private:
int hour, minute, second;
public:
Time(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
friend class Date;
};
class Date {
private:
int day, month, year;
public:
Date(int d, int m, int y) {
day = d;
month = m;
year = y;
}
void display(Time &t) {
cout << day << "-" << month << "-" << year << " " << t.hour << ":" << t.minute << ":" << t.second << endl;
}
};
int main() {
Time t(10, 30, 59);
Date d(12, 6, 2021);
d.display(t);
return 0;
}
```
在上述代码中,`Date` 类中的 `display` 函数接受一个 `Time` 类型的对象的引用作为参数,然后使用该对象的私有成员变量 `hour`、`minute` 和 `second` 输出时间信息。在 `main` 函数中,创建了一个 `Time` 类型的对象 `t` 和一个 `Date` 类型的对象 `d`,然后通过调用 `d` 对象的 `display` 函数输出日期和时间信息。输出结果为:
```
12-6-2021 10:30:59
```