C++继承和派生练习(一)--关于从people(人员)类派生出student(学生)类等
时间: 2023-12-19 14:04:13 浏览: 116
1. 定义people类,包含以下成员变量和成员函数:
```cpp
class people {
private:
string name;
int age;
char gender;
string phone;
public:
people(string n, int a, char g, string p);
void display();
};
```
其中,构造函数people(string n, int a, char g, string p)用于初始化成员变量;display()函数用于显示人员信息。
2. 从people类中派生出student类,包含以下成员变量和成员函数:
```cpp
class student : public people {
private:
string id;
string major;
public:
student(string n, int a, char g, string p, string i, string m);
void display();
};
```
其中,构造函数student(string n, int a, char g, string p, string i, string m)用于初始化成员变量;display()函数用于显示学生信息。
3. 实现people类和student类的成员函数:
```cpp
people::people(string n, int a, char g, string p) {
name = n;
age = a;
gender = g;
phone = p;
}
void people::display() {
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
cout << "性别:" << gender << endl;
cout << "电话:" << phone << endl;
}
student::student(string n, int a, char g, string p, string i, string m) : people(n, a, g, p) {
id = i;
major = m;
}
void student::display() {
people::display();
cout << "学号:" << id << endl;
cout << "专业:" << major << endl;
}
```
4. 编写测试代码,验证people类和student类的功能:
```cpp
int main() {
people p("张三", 20, 'M', "13888888888");
p.display();
student s("李四", 18, 'F', "13999999999", "2021000001", "计算机科学与技术");
s.display();
return 0;
}
```
输出结果如下:
```
姓名:张三
年龄:20
性别:M
电话:13888888888
姓名:李四
年龄:18
性别:F
电话:13999999999
学号:2021000001
专业:计算机科学与技术
```