定义一个人员CPerson类,包含数据成员年龄和姓名,定义一个CPerson类的派生类教师CTeacher类,包含数据成员专业和职称。分别为两个类定义带参数的构造函数初始化,再分别定义display()函数输出信息。将display()函数定义为虚函数,并用CPerson类的指针分别指向CPerson类和CTeacher类的对象,实现多态。编写主函数测试如果年龄小于26岁,则提示"Input Error!"并结束程序。。
时间: 2024-03-16 21:47:18 浏览: 58
设计一个Person类,有Person类派生一个Student类和一个Teacher类
好的,下面是代码实现:
```c++
#include <iostream>
#include <string>
using namespace std;
class CPerson {
protected:
int age;
string name;
public:
CPerson(int a, string n): age(a), name(n) {}
virtual void display() {
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
}
};
class CTeacher : public CPerson {
private:
string major;
string jobTitle;
public:
CTeacher(int a, string n, string m, string j): CPerson(a, n), major(m), jobTitle(j) {}
void display() {
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
cout << "专业:" << major << endl;
cout << "职称:" << jobTitle << endl;
}
};
int main() {
int age;
string name, major, jobTitle;
cout << "请输入姓名:";
cin >> name;
cout << "请输入年龄:";
cin >> age;
if (age < 26) {
cout << "Input Error!" << endl;
return 0;
}
cout << "请输入专业:";
cin >> major;
cout << "请输入职称:";
cin >> jobTitle;
CPerson* person = new CPerson(age, name);
person->display();
cout << endl;
CTeacher* teacher = new CTeacher(age, name, major, jobTitle);
CPerson* person2 = teacher;
person2->display();
delete person;
delete teacher;
return 0;
}
```
在上面的代码中,我们在输入年龄时添加了判断,如果年龄小于 26 岁,则输出错误提示并结束程序。
阅读全文