c++创建一个生日类,该类包含年和月属性;创建学生类,其中包含生日类对象,设计学生类其余属性及函数,最终输出学生所有信息。
时间: 2024-02-27 18:55:29 浏览: 42
好的,我来为您解答这个问题。
首先,我们需要定义一个生日类,包含年和月属性:
```c++
class Birthday {
private:
int year;
int month;
public:
Birthday(int y, int m): year(y), month(m) {}
int getYear() const { return year; }
int getMonth() const { return month; }
};
```
接下来,我们可以定义一个学生类,其中包含一个生日类对象,以及其他属性和函数:
```c++
class Student {
private:
string name;
int age;
Birthday birthday;
public:
Student(string n, int a, int y, int m): name(n), age(a), birthday(y, m) {}
string getName() const { return name; }
int getAge() const { return age; }
Birthday getBirthday() const { return birthday; }
void setName(string n) { name = n; }
void setAge(int a) { age = a; }
void setBirthday(int y, int m) { birthday = Birthday(y, m); }
void displayInfo() const {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Birthday: " << birthday.getYear() << "-" << birthday.getMonth() << endl;
}
};
```
在上面的代码中,我们定义了一个 Student 类,包含了名字、年龄和生日等属性,以及 get 和 set 函数,用于访问和修改这些属性。还定义了一个 displayInfo 函数,用于输出学生的所有信息。
最后,我们可以在主函数中创建一个学生对象,并输出它的信息:
```c++
int main() {
Student student("John Doe", 18, 2003, 5);
student.displayInfo();
return 0;
}
```
输出结果如下:
```
Name: John Doe
Age: 18
Birthday: 2003-5
```
这就是一个简单的 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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)