C++继承和派生练习(一)--关于从people(人员)类派生出student(学生)类等
时间: 2023-08-03 13:04:55 浏览: 49
好的,让我们开始。
首先,我们需要创建一个人员类 People。这个类应该包含基本属性,比如姓名和年龄,并且应该有一个显示这些属性的方法。以下是一个可能的 People 类的代码:
```cpp
class People {
private:
string name;
int age;
public:
void setName(string n) { name = n; }
void setAge(int a) { age = a; }
string getName() { return name; }
int getAge() { return age; }
void display() { cout << "Name: " << name << "\nAge: " << age << endl; }
};
```
接下来我们需要创建一个学生类 Student,它从 People 类派生而来。这个类应该包含 People 类的所有属性,并且应该还有一个学生特有的属性,比如学号。以下是一个可能的 Student 类的代码:
```cpp
class Student : public People {
private:
string studentId;
public:
void setStudentId(string id) { studentId = id; }
string getStudentId() { return studentId; }
void display() {
cout << "Name: " << getName() << "\nAge: " << getAge() << "\nStudent ID: " << studentId << endl;
}
};
```
在这个代码中,我们使用了 public 关键字来表示 Student 类从 People 类公开继承。这意味着我们可以在 Student 类中使用 People 类的所有公共成员函数和变量。我们还添加了一个新的属性 studentId,并且重写了 display 方法,以便能够显示学生特有的属性。
现在我们可以创建一个 Student 对象并设置它的属性:
```cpp
int main() {
Student student;
student.setName("Alice");
student.setAge(20);
student.setStudentId("12345");
student.display();
return 0;
}
```
这个程序应该输出以下内容:
```
Name: Alice
Age: 20
Student ID: 12345
```
这就是从 People 类派生出 Student 类的基础练习。希望对你有所帮助!
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![cpp](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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)