定义一个人员CPerson类,包含数据成员年龄和姓名,定义一个CPerson类的派生类教师CTeacher类,包含数据成员专业和职称。分别为两个类定义带参数的构造函数初始化,再分别定义display()函数输出信息。将display()函数定义为虚函数,并用CPerson类的指针分别指向CPerson类和CTeacher类的对象,实现多态。编写主函数测试。 【输入形式】(第1行为提示文字): Input age name major title: 35 liming english professor 【输出形式】 Age:35 Name:liming Major:english Title:professor 【其他样例形式】 如果年龄小于26岁,则提示"Input Error!"并结束程序。 如下: Input age name major title: Input Error!
时间: 2024-03-17 17:41:24 浏览: 106
下面是代码实现:
```
#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<<"Age:"<<age<<"\nName:"<<name<<endl;
}
};
class CTeacher:public CPerson{
private:
string major;
string title;
public:
CTeacher(int a, string n, string m, string t):CPerson(a, n), major(m), title(t){}
void display(){
cout<<"Age:"<<age<<"\nName:"<<name<<"\nMajor:"<<major<<"\nTitle:"<<title<<endl;
}
};
int main(){
int age;
string name, major, title;
cin>>age>>name>>major>>title;
if(age<26){
cout<<"Input Error!"<<endl;
return 0;
}
CPerson* person = new CPerson(age, name);
CTeacher* teacher = new CTeacher(age, name, major, title);
person->display();
teacher->display();
delete person;
delete teacher;
return 0;
}
```
输入样例:
```
35 liming english professor
```
输出样例:
```
Age:35
Name:liming
Age:35
Name:liming
Major:english
Title:professor
```
阅读全文