4、创建一个类,要求含有成员变量、构造函数、成员函数;编写一子类重写父类的成员函数, 用实例测试父类和子类并运行(最好能有输出结果并显示)
时间: 2023-06-01 13:05:21 浏览: 54
没问题,我可以回答这个问题。您可以参考以下代码。
```
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
Person(string n, int a) {
name = n;
age = a;
}
void displayInfo() {
cout << name << " is " << age << " years old." << endl;
}
};
class Student : public Person {
public:
string major;
Student(string n, int a, string m) : Person(n, a) {
major = m;
}
void displayInfo() {
cout << name << " is " << age << " years old and is majoring in " << major << "." << endl;
}
};
int main() {
Person p("John", 25);
p.displayInfo();
Student s("Jane", 20, "Computer Science");
s.displayInfo();
return 0;
}
```
这里我们创建了一个Person类和一个继承自Person的Student类。Person类有name和age两个成员变量以及一个构造函数和一个displayInfo函数用于显示个人信息。Student类在Person类的基础上增加了major成员变量和一个能够显示学生信息的displayInfo函数。我们在main函数中创建了一个Person对象和一个Student对象,并调用它们的displayInfo函数分别输出它们的信息。
运行结果:
```
John is 25 years old.
Jane is 20 years old and is majoring in Computer Science.
```