person作为虚基类派生学生类和教师类
时间: 2023-12-19 20:05:47 浏览: 96
可以这样定义一个Person类作为虚基类:
```c++
class Person {
public:
virtual void printInfo() const = 0;
virtual ~Person() {}
};
```
然后我们可以分别派生出Student类和Teacher类,并实现各自的printInfo()函数:
```c++
class Student : virtual public Person {
private:
std::string name;
int age;
std::string school;
public:
Student(const std::string& name, int age, const std::string& school)
: name(name), age(age), school(school) {}
void printInfo() const override {
std::cout << "Name: " << name << ", Age: " << age << ", School: " << school << std::endl;
}
};
class Teacher : virtual public Person {
private:
std::string name;
int age;
std::string department;
public:
Teacher(const std::string& name, int age, const std::string& department)
: name(name), age(age), department(department) {}
void printInfo() const override {
std::cout << "Name: " << name << ", Age: " << age << ", Department: " << department << std::endl;
}
};
```
注意在派生类中,我们都使用了`virtual public Person`来继承Person类,这是为了避免在多重继承中产生二义性。同时我们也实现了纯虚函数`printInfo()`,这是因为Person类本身没有意义,只是作为一个基类存在,我们只需要让它的子类实现相应的函数即可。
这样,我们就可以使用以下代码来创建学生和教师对象并输出信息:
```c++
int main() {
Person* p1 = new Student("Alice", 18, "MIT");
Person* p2 = new Teacher("Bob", 35, "Computer Science");
p1->printInfo();
p2->printInfo();
delete p1;
delete p2;
return 0;
}
```
输出为:
```
Name: Alice, Age: 18, School: MIT
Name: Bob, Age: 35, Department: Computer Science
```
阅读全文