中易网

程序中有两个类,一个是父类、一个是子类,子类从父类public方式派生

答案:2  悬赏:0  
解决时间 2021-04-28 00:12
  • 提问者网友:无心恋土
  • 2021-04-27 06:22

程序中有两个类,一个是父类、一个是子类,子类从父类public方式派生。子类和父类中都有一个形式完全一样的display函数,父类中display函数显示父类的成员信息,子类中的display函数仅显示子类新添加的成员信息(所有成员信息为私有的),要求主程序中能通过子类对象将子类的所有成员信息显示出来。另外可在类中添加虚函数,通过基类指针或引用,实现多态。

最佳答案
  • 二级知识专家网友:悲观垃圾
  • 2021-04-27 07:26

#include <iostream>
#include <string>


using namespace std;


class Parent
{
 string Name;
 int Age;
public:
 Parent(string name="noname",int age=20):Name(name),Age(age){}
 virtual void display();
};


void Parent::display()
{
 cout<<"姓名:"<<Name<<" 年龄:"<<Age<<endl;
}


class Child:public Parent
{
public:
 Child(string name,int age):Parent(name,age){}
 virtual void display();
};


void Child::display()
{
 cout<<"学生 ";
 Parent::display();
}


int main()
{
 Parent p("Mr. chen",21);
 cout<<"老师 ";
 p.display();


 Child c("Lin",22);
 c.display();
}


全部回答
  • 1楼网友:野性且迷人
  • 2021-04-27 08:22
#include #include using namespace std; class Student { public : void display(); void get_value(); protected: int num; string name; char sex; }; void Student::display() { cout <<"num:"<>num; cin>>name; cin>>sex; } class Student1:public Student { public : void display1(); void get_value_1(); private : int age; string addr; }; void Student1::get_value_1() { cin>>age; cin>>addr; } void Student1::display1() { cout<<"age:"<<age<<endl; cout<<"address:"<<addr<<endl; } main() { Student1 stud1; cout<<" 请输入5个数据:"<<endl; stud1.get_value(); stud1.get_value_1(); stud1.display(); stud1.display1(); return 0 ; }
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!
大家都在看
推荐信息