用c++创建一个生日类,该类包含年和月属性;创建学生类,其中包含生日类对象,设计学生类其余属性及函数,最终输出学生所有信息
时间: 2024-02-05 13:04:48 浏览: 33
好的,我们可以先定义生日类,包含年和月属性:
```c++
class Birthday {
public:
Birthday(int year, int month) : _year(year), _month(month) {} // 构造函数
int getYear() const { return _year; } // 获取年份
int getMonth() const { return _month; } // 获取月份
private:
int _year; // 年份
int _month; // 月份
};
```
接下来,我们定义学生类,包含姓名、性别、生日等属性和一些函数。
```c++
class Student {
public:
Student(const std::string& name, const std::string& gender, const Birthday& birthday)
: _name(name), _gender(gender), _birthday(birthday) {} // 构造函数
std::string getName() const { return _name; } // 获取姓名
std::string getGender() const { return _gender; } // 获取性别
Birthday getBirthday() const { return _birthday; } // 获取生日
void setName(const std::string& name) { _name = name; } // 修改姓名
void setGender(const std::string& gender) { _gender = gender; } // 修改性别
void setBirthday(const Birthday& birthday) { _birthday = birthday; } // 修改生日
void printInfo() const { // 输出学生信息
std::cout << "Name: " << _name << std::endl;
std::cout << "Gender: " << _gender << std::endl;
std::cout << "Birthday: " << _birthday.getYear() << "-" << _birthday.getMonth() << std::endl;
}
private:
std::string _name; // 姓名
std::string _gender; // 性别
Birthday _birthday; // 生日
};
```
最后,我们可以在 main 函数中创建一个学生对象,调用 printInfo() 函数输出学生信息。
```c++
int main() {
Birthday birthday(2000, 6);
Student student("Tom", "Male", birthday);
student.printInfo();
return 0;
}
```
输出结果如下:
```
Name: Tom
Gender: Male
Birthday: 2000-6
```
这样,我们就完成了用 C++ 创建一个生日类和一个学生类,并输出学生信息的问题的设计和实现。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![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://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)