分析#include <iostream> using namespace std; class Date { public: Date(int month, int day, int year) { year = year; month = month; day = day; } Date(int month, int day) { year = 2000; month = month; day = day; } Date(); ~Date() {}; void show() const; private: int year{}; int month{}; int day{}; }; class People { private: int number, id; bool sex; Date birthday; public: People(int number, int id, bool sex, Date birthday); People(People &p); ~People() {}; void getNumber() const; void getSex() const; void getId() const; inline void setSex(bool sx) { sex = sx; }; void show(); }; void Date::show() const { cout << "生日:" << year << "年" << month << "月" << day << "日" << endl; } Date::Date() {} void People::show() { People::getSex(); People::getId(); People::getNumber(); People::birthday.show(); } void People::getId() const { cout << id << endl; } void People::getNumber() const { cout << number << endl; } void People::getSex() const { if (sex == 0) cout << "女" << endl; else cout << "男" << endl; } People::People(int number, int id, bool sex, Date birthday) { People::number = number; People::sex = sex; People::id = id; People::birthday = birthday; } People::People(People &p) { id = p.id; sex = p.sex; birthday = p.birthday; number = p.number; } int main() { Date dd(15, 2); People pp(456, 135132, 1, dd); pp.setSex(false); pp.show(); Date d(15, 2, 2001); People p(123, 130031, 1, d); p.show(); }
时间: 2023-12-30 10:02:46 浏览: 119
#include <iostream>
这段代码定义了两个类:Date和People。其中,Date类表示日期,People类表示人。People类包含了一个Date类的成员变量birthday,表示人的生日。
在main函数中,首先创建了一个Date对象dd和一个People对象pp,然后调用pp的setSex方法将其性别设置为女性,最后调用pp的show方法输出该人的信息,包括编号、身份证号、性别和生日。
接着创建了另外一个Date对象d和一个People对象p,同样调用p的show方法输出该人的信息。不同之处在于,p的生日是在构造函数中直接传入3个参数初始化的,而不是像pp一样在构造函数中传入一个Date对象。
需要注意的是,在Date类的构造函数中有两个重载,分别接受2个和3个参数,但是两个构造函数中的参数名都与成员变量名相同,这会导致在构造函数中无法正确地初始化成员变量。正确的做法是在构造函数中使用this指针来引用成员变量,例如:
```
Date(int month, int day, int year) {
this->year = year;
this->month = month;
this->day = day;
}
```
阅读全文