设计一个日期类和时间类,编写display函数用于显示日期和时间。要求:display函数作为类外的普通函数,分别在Time和Date类中将display声明为友元函数。在主函数中调用display函数,display函数分别引用Time和Date两个类的对象的私有数据,输出年、月、日和时、分、秒。
时间: 2024-03-26 16:35:58 浏览: 19
好的,以下是代码实现:
```cpp
#include <iostream>
using namespace std;
class Time; // 前置声明
class Date {
private:
int year, month, day;
public:
Date(int y = 0, int m = 0, int d = 0) : year(y), month(m), day(d) {}
friend void display(Date &d, Time &t);
};
class Time {
private:
int hour, minute, second;
public:
Time(int h = 0, int m = 0, int s = 0) : hour(h), minute(m), second(s) {}
friend void display(Date &d, Time &t);
};
void display(Date &d, Time &t) {
cout << "Date: " << d.year << "-" << d.month << "-" << d.day << endl;
cout << "Time: " << t.hour << ":" << t.minute << ":" << t.second << endl;
}
int main() {
Date d(2021, 10, 1);
Time t(12, 30, 45);
display(d, t);
return 0;
}
```
输出结果为:
```
Date: 2021-10-1
Time: 12:30:45
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)