设计一个日期类和时间类,编写display函数用于显示日期和时间。要求:display函数作为类外的普通函数,分别在Time和Date类中将display声明为友元函数。在主函数中调用display函数,display函数分别引用Time和Date两个类的对象的私有数据,输出年、月、日和时、分、秒。
时间: 2024-03-23 22:41:38 浏览: 30
好的,我会为您解答这个问题。
首先,我们需要设计一个日期类和一个时间类。时间类可以包含小时、分钟和秒,而日期类可以包含年、月和日。下面是代码实现:
```cpp
class Time {
private:
int hour;
int minute;
int second;
public:
Time(int h=0, int m=0, int s=0) {
hour = h;
minute = m;
second = s;
}
friend void display(const Time& t);
};
class Date {
private:
int year;
int month;
int day;
public:
Date(int y=0, int m=0, int d=0) {
year = y;
month = m;
day = d;
}
friend void display(const Date& d);
};
```
接下来,我们要编写display函数,它将被声明为友元函数,并在类外定义。这个函数需要引用Time和Date两个类的对象的私有数据,并输出年、月、日和时、分、秒。下面是代码实现:
```cpp
void display(const Time& t) {
std::cout << t.hour << ":" << t.minute << ":" << t.second << std::endl;
}
void display(const Date& d) {
std::cout << d.year << "-" << d.month << "-" << d.day << std::endl;
}
```
最后,在主函数中创建一个Time对象和一个Date对象,然后调用display函数输出它们的私有数据。下面是代码实现:
```cpp
int main() {
Time t(10, 30, 45);
Date d(2021, 11, 11);
display(t);
display(d);
return 0;
}
```
这样就完成了题目要求的所有内容。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)