C++继承和派生练习(一)--关于从people(人员)类派生出student(学生)类等
时间: 2023-08-28 18:03:45 浏览: 75
好的,我理解了你的问题。让我们来看一下如何从`People`类派生出`Student`类。
首先,我们需要定义`People`类。`People`类应该包含人员的基本属性,例如姓名、年龄、性别等。
```cpp
class People {
public:
People(string name, int age, string gender) {
this->name = name;
this->age = age;
this->gender = gender;
}
string getName() {
return this->name;
}
int getAge() {
return this->age;
}
string getGender() {
return this->gender;
}
private:
string name;
int age;
string gender;
};
```
接下来,我们定义`Student`类,它是从`People`类派生而来。`Student`类应该包含`People`类中的所有属性,以及学生特有的属性,例如学号、班级等。
```cpp
class Student : public People {
public:
Student(string name, int age, string gender, int studentId, string className)
: People(name, age, gender) {
this->studentId = studentId;
this->className = className;
}
int getStudentId() {
return this->studentId;
}
string getClassName() {
return this->className;
}
private:
int studentId;
string className;
};
```
在这里,我们使用了`public`继承来继承`People`类。这意味着`Student`类中的所有公共成员都可以访问`People`类中的公共成员。
我们可以创建一个`Student`对象并访问它的属性,例如:
```cpp
Student student("张三", 18, "男", 1001, "一班");
cout << "姓名:" << student.getName() << endl;
cout << "年龄:" << student.getAge() << endl;
cout << "性别:" << student.getGender() << endl;
cout << "学号:" << student.getStudentId() << endl;
cout << "班级:" << student.getClassName() << endl;
```
输出结果应该为:
```
姓名:张三
年龄:18
性别:男
学号:1001
班级:一班
```
希望这个例子可以帮助你理解如何从`People`类派生出`Student`类。如果你还有其他问题,请随时问我。