2979: MathBook类--多态
时间限制: 1 Sec 内存限制: 128 MB提交: 51 解决: 31
题目描述
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 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; } void MathBook::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; MathBook math(price,page,difficulty); Book *p=&book; p->display(); cout<<endl; p=&math; p->display(); return 0; }