2636: B3 指向基类的指针访问派生类的成员函数


时间限制: 1 Sec   内存限制: 128 MB

提交: 433  

解决: 141


题目描述


领导类(Leader)和工程师类(Engineer)都是人类(Person)的派生类。请将下面代码中空缺的部分填上,使main函数中能通过指向Person类的指针,调用Leader和Engineer类中各自的成员函数show,输出相关的信息


//************* begin *****************




#include <iostream>




using namespace std;




class Person




{




public:




Person(string na, int a):name(na),age(a) {}




___(1)_____ show() ___(2)___;




protected:




string name; // 姓名




int age; // 年龄




};





class Leader: ___(3)_____ Person




{




private:




string job; // 职务




string dep; // 部门




public:




Leader(string na, int a, string j, string d): ____(4)______{ }




void show(){____(5)____}




};




//************* end *****************




class Engineer: public Person




{




string major; // 专业




public:




Engineer (string na, int a, string m): Person(na, a),major(m){ }




void show(){cout<<name<<" is an engineer of "<<major<<" major."<<endl;}




};





int main()




{




Person *p;




string name, job, dept,major;




int age;





cin>>name>>age>>job>>dept;




p=new Leader(name,age,job,dept);




p->show();





cin>>name>>age>>major;




p=new Engineer(name,age,major);




p->show();




return 0;




}



输入


第一行输入是某领导的信息,如“Wang 40 Manager Sales”表示40岁的王(Wang)领导是销售部(Sales)的经理(Manager)。



第二行输入某工程师的信息,如“Zhang 30 Software”表示30岁的张(Zhang)是工程师,他的专业是软件(Software)




输出


规定的格式输出信息,请注意空格及最后的标点。




样例输入

Wang 40 Manager Sales
Zhang 30 Software

样例输出

Wang is Manager in Sales department.
Zhang is an engineer of Software major.

迷失在幽谷中的鸟儿,独自飞翔在这偌大的天地间,却不知自己该飞往何方……


#include <iostream>
using namespace std;
class Person
{
public:
Person(string na, int a):name(na),age(a) {}
virtual void show();

protected:
string name; // 姓名
int age; // 年龄
};
class Leader: public Person
{
private:
string job; // 职务
string dep; // 部门
public:
Leader(string na, int a, string j, string d): Person(na,a),job(j),dep(d) { }
void show();
};
void Person::show()
{
cout<<name;
}
void Leader::show()
{
Person::show();
cout<<" is "<<job<<" in "<<dep<<" department."<<endl;
}
class Engineer: public Person
{
string major1; // 专业
public:
Engineer (string na, int a, string m): Person(na, a),major1(m) { }
void show()
{
cout<<name<<" is an engineer of "<<major1<<" major."<<endl;
}
};
int main()
{
Person *p;
string name, job, dept,major;
int age;
cin>>name>>age>>job>>dept;
p=new Leader(name,age,job,dept);
p->show();
cin>>name>>age>>major;
p=new Engineer(name,age,major);
p->show();
return 0;
}