设计person类,包括私有数据成员:姓名、性别和年龄;设计student类继承person类,新增私有数据成员:班级;设计类
时间: 2024-02-23 10:57:50 浏览: 81
以下是C++语言的实现示例:
```c++
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
char gender;
int age;
public:
Person(string n, char g, int a) {
name = n;
gender = g;
age = a;
}
void display() {
cout << "Name: " << name << endl;
cout << "Gender: " << gender << endl;
cout << "Age: " << age << endl;
}
};
class Student : public Person {
private:
string className;
public:
Student(string n, char g, int a, string c) : Person(n, g, a) {
className = c;
}
void display() {
Person::display();
cout << "Class: " << className << endl;
}
};
int main() {
Person p("Tom", 'M', 20);
Student s("Lucy", 'F', 18, "Class A");
p.display();
s.display();
return 0;
}
```
上述代码中,Person类有三个私有数据成员:姓名、性别和年龄。Student类继承了Person类,并新增了一个私有数据成员:班级。在构造函数中,Student类的构造函数调用了Person类的构造函数,并将班级名称传入。在display()函数中,Student类的display()函数先调用了Person类的display()函数,再输出班级名称。在main()函数中,分别创建了一个Person对象和一个Student对象,并调用它们的display()函数。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.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/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)