创建一个生日类,该类包含年和月属性;创建学生类,其中包含生日类对象,设计学生类其余属性及函数,最终输出学生所有信息。用c++
时间: 2024-03-07 15:47:27 浏览: 18
好的,以下是示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
class Birthday {
public:
Birthday(int y, int m) : year(y), month(m) {}
int year;
int month;
};
class Student {
public:
Student(string n, char g, Birthday b) : name(n), gender(g), birthday(b) {}
void setScore(double s) { score = s; }
void printInfo() {
cout << "Name: " << name << endl;
cout << "Gender: " << gender << endl;
cout << "Birthday: " << birthday.year << "-" << birthday.month << endl;
cout << "Score: " << score << endl;
}
private:
string name;
char gender;
Birthday birthday;
double score;
};
int main() {
Birthday b(2000, 8);
Student s("Tom", 'M', b);
s.setScore(90.5);
s.printInfo();
return 0;
}
```
在上面的代码中,我们首先定义了一个 `Birthday` 类,包含了年和月两个属性。然后定义了一个 `Student` 类,其中包含了一个 `Birthday` 类的对象,以及学生的其他属性和函数。
在 `main` 函数中,我们创建了一个 `Birthday` 类的对象 `b`,然后用它来创建一个 `Student` 类的对象 `s`,并设置了学生的成绩。最后调用 `printInfo` 函数输出学生的信息。