利用c++编写代码,有一个日期类Date,它有私有数据y,m,d。此类的对象作为另一个类的私有数据,用以描述一个人的姓名、出生日期及性别。编写必要的成员函数,并在main函数中进行测试。
时间: 2024-02-20 15:01:56 浏览: 21
好的,以下是代码实现:
```cpp
#include <iostream>
using namespace std;
class Date {
private:
int y, m, d;
public:
Date(int year, int month, int day) : y(year), m(month), d(day) {}
int getYear() const {
return y;
}
int getMonth() const {
return m;
}
int getDay() const {
return d;
}
};
class Person {
private:
string name;
Date birthDate;
char gender;
public:
Person(string n, Date d, char g) : name(n), birthDate(d), gender(g) {}
string getName() const {
return name;
}
Date getDate() const {
return birthDate;
}
char getGender() const {
return gender;
}
};
int main() {
Date d(2000, 1, 1);
Person p("Tom", d, 'M');
cout << "Name: " << p.getName() << endl;
cout << "Birth Date: " << p.getDate().getYear() << "-" << p.getDate().getMonth() << "-" << p.getDate().getDay() << endl;
cout << "Gender: " << p.getGender() << endl;
return 0;
}
```
我们定义了两个类,一个是Date,一个是Person。其中,Person类的私有数据包含了姓名、出生日期和性别,其中出生日期用到了Date类。在main函数中,我们创建了一个Person对象,并输出其姓名、出生日期和性别。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.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)