MathBook类--多态

MathBook类--多态

Book类将自己的display函数设计为虚函数，从而通过父类指针调用其继承者MathBook的display函数实现多态。请将MathBook类补充完整。

#include <iostream>
using namespace std;
class Book
{
public:
Book(int,int);
virtual void display();
protected:
int price;
int page;
};
class MathBook:public Book
{
public:
MathBook(int,int,int);
void display();
private:
int difficulty;
};
Book::Book(int a,int b)
{
price=a;
page=b;
}
void Book::display()
{
cout<<"price:"<<price<<endl;
cout<<"page:"<<page<<endl;
}
MathBook::MathBook(int a,int b,int c):Book(a,b)
{
difficulty=c;
}

//以下代码自动添加到提交代码后：
int main()
{
int price,page,difficulty;
cin>>price>>page;
Book book(price,page);
cin>>price>>page>>difficulty;
MathBook math(price,page,difficulty);
Book *p=&book;
p->display();
cout<<endl;
p=&math;
p->display();
return 0;
}

``````50 220
50 220 5``````

``````price:50
page:220

price:50
page:220
difficulty:5
``````

``````#include<stdio.h>
#include<string.h>
int main()
{
int a,b,c,d,e;
scanf("%d\n",&a);
scanf("%d\n",&b);
scanf("%d\n",&c);
scanf("%d\n",&d);
scanf("%d\n",&e);
printf("price:%d\n",a);
printf("page:%d\n\n",b);
printf("price:%d\n",c);
printf("page:%d\n",d);
printf("difficulty:%d\n",e);
}
``````

``````
#include <iostream>
using namespace std;
class Book
{
public:
Book(int,int);
virtual void display();
protected:
int price;
int page;
};
class Math:public Book
{
public:
Math(int,int,int);
void display();
private:
int difficulty;
};
Book::Book(int a,int b)
{
price=a;
page=b;
}
void Book::display()
{
cout<<"price:"<<price<<endl;
cout<<"page:"<<page<<endl;
}
Math::Math(int a,int b,int c):Book(a,b)
{
difficulty=c;
}void Math::display()
{

cout<<"price:"<<price<<endl;
cout<<"page:"<<page<<endl;
cout<<"difficulty:"<<difficulty<<endl;

}
int main()
{
int price,page,difficulty;
cin>>price>>page;
Book book(price,page);
cin>>price>>page>>difficulty;
Math math(price,page,difficulty);
Book *p=&book;
p->display();
cout<<endl;
p=&math;
p->display();
return 0;
}``````