使用c++进行编程Person类派生大学生CollegeStu类。 (1)设计一个Person类,其属性包括姓名name和身份证号id,其中name为字符串类型,id为整型,编写成员函数: 构造函数Person、Display函数 ( 显示数据成员信息)和析构函数; (2)由Person类派生出大学生类CollegeStu,其属性有专业maior ( 字符串类型),C++程设计课程成绩score ( double型 ),编写构造函数( 实现数据初始化 )、输出函数Display ( 包括name,id , major , score )。
时间: 2024-02-21 10:59:53 浏览: 81
好的,这是一个简单的继承例子,下面是C++代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int id;
public:
Person(string n, int i): name(n), id(i) { }
void Display() {
cout << "Name: " << name << endl;
cout << "ID: " << id << endl;
}
~Person() { }
};
class CollegeStu : public Person {
private:
string major;
double score;
public:
CollegeStu(string n, int i, string m, double s): Person(n, i), major(m), score(s) { }
void Display() {
Person::Display();
cout << "Major: " << major << endl;
cout << "Score: " << score << endl;
}
~CollegeStu() { }
};
int main() {
CollegeStu stu("Tom", 123456, "Computer Science", 95.5);
stu.Display();
return 0;
}
```
在Person类中,我们定义了两个私有数据成员name和id,并在构造函数中初始化它们。Display函数用于显示Person对象的数据成员信息。
在CollegeStu类中,我们使用public继承Person类,并新增了两个私有数据成员major和score,同时在构造函数中使用Person类的构造函数初始化name和id,使用初始化列表初始化major和score。Display函数使用Person类的Display函数来输出name和id,并输出新增加的major和score。
最后,在main函数中,我们创建了一个CollegeStu对象stu,并调用它的Display函数来输出所有数据成员信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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://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://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://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://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)