Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
Problem Description
通过本题目的练习可以掌握多态性的概念和虚函数的定义和使用方法
要求定义一个基类Pet,它有一个字符指针型数据成员name和一个虚成员函数Speak()用于输出pet的叫声。;派生类Dog和Cat从基类Pet派生而来。他们从基类继承并重新改写了speak()函数,分别用于输出Dog类和Cat类的叫声(具体输出内容参考示例输出)。要求利用虚函数技术编写代码,使得程序能够输出下面的内容。
Input
无
Output
输出数据共有3行,本题目要求输出内容必须与示例中的相同。
Example Input
Example Output
How does a pet speak ?
I am a cat,My name is Tom My sound is miao!miao!
I am a dog,My name is Snoppy My sound is wang!wang!
Hint
Author
黄晶晶
#include<iostream>
using namespace std;
class Pet
{
public:
Pet()
{
name="Pet";
}
virtual void speak()
{
cout<<"How does a pet speak ?"<<endl;
}
protected:
string name;
};
class cat:public Pet
{
public:
cat()
{
this->name="Tom";
}
void speak()
{
cout<<"I am a cat,My name is ";
cout<<name;
cout<<" My sound is miao!miao!"<<endl;
}
};
class dog:public Pet
{
public:
dog()
{
this->name="Snoppy";
}
void speak()
{
cout<<"I am a dog,My name is ";
cout<<name;
cout<<" My sound is wang!wang!"<<endl;
}
};
int main()
{
Pet p,*q;
dog d;
cat c;
q=&p;
q->speak();
q=&c;
q->speak();
q=&d;
q->speak();
}