定义一个Date类 数据成员:年,月,日 成员函数:有参构造函数 定义一个Time类 数据成员:时,分,秒 成员函数:有参构造函数 定义一个普通函数show,它既是Date的友元函数,也是Time的友元函数。 在main函数中定义Date,Time对象,调用show函数,输出当前的日期和时间。
时间: 2024-03-10 18:49:33 浏览: 123
好的,我可以为您写一个基本的实现。请注意,以下代码仅为示例,可能需要根据您的实际需求进行更改。
```c++
#include <iostream>
using namespace std;
class Time;
class Date {
private:
int year;
int month;
int day;
public:
Date(int y, int m, int d) {
year = y;
month = m;
day = d;
}
friend void show(Date d, Time t);
};
class Time {
private:
int hour;
int minute;
int second;
public:
Time(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
friend void show(Date d, Time t);
};
void show(Date d, Time t) {
cout << "Current date: " << d.year << "-" << d.month << "-" << d.day << endl;
cout << "Current time: " << t.hour << ":" << t.minute << ":" << t.second << endl;
}
int main() {
Date d(2022, 12, 31);
Time t(23, 59, 59);
show(d, t);
return 0;
}
```
在上面的代码中,我们首先定义了 Date 类和 Time 类,并在其中分别定义了构造函数。然后,我们将 show 函数声明为这两个类的友元函数,以便它可以访问它们的私有成员。在 show 函数中,我们将当前的日期和时间输出到控制台。最后,在 main 函数中,我们创建了一个 Date 对象和一个 Time 对象,并将它们传递给 show 函数以显示当前的日期和时间。
阅读全文
相关推荐
















