内存:128  时间:1

题目描述

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

只需提交补充部分。

请用C++方式提交

以下代码自动添加到提交代码前:
#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;
}

输入

第一行输入book对象的price和page;
第二行输入math对象的price、page和difficulty

输出

两个对象的信息

样例输入

50 220
50 220 5

样例输出

price:50
page:220

price:50
page:220
difficulty:5

提示

代码如下


#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;
}

代码来源于互联网,仅供参考!