动物说话术
请修改编辑器中的代码,完成以下功能:完善 Animal 类及其派生类 Dog、Cat,并实现输出函数,按下面两行的格式介绍一只动物: 名字 is a 类型. 名字 says 叫声. 主函数会依次介绍基类对象、一只狗和一只猫,通过基类引用调用虚函数实现多态。程序不需要输入。 输出示例: Animal is a Animal. Animal says Voice. Lucky is a Dog. Lucky says Woof. Daisy is a Cat. Daisy says Miaow.
#include <iostream>
#include <cstring>
#pragma warning (disable:4996)
using namespace std;
class Animal
{
public:
Animal(const char* str="Animal")
{
//**********found**********
name = new ___________________;
strcpy(name,str);
}
virtual ~Animal() { delete[] name; }
const char* getName() const { return name; }
virtual const char* getType() const { return "Animal"; }
virtual const char* getVoice() const { return "Voice"; }
protected:
char* name;
};
class Dog : public Animal
{
public:
Dog(const char* str) : Animal(str) {}
const char* getType() const { return "Dog"; }
const char* getVoice() const { return "Woof"; }
};
class Cat: public Animal
{
public:
Cat(const char* str) : Animal(str) {}
const char* getType() const { return "Cat"; }
const char* getVoice() const { return "Miaow"; }
};
void Speak(Animal& animal)
{
//**********found**********
cout<<animal.getName()<<" is a "<<__________________<<"."<<endl;
cout<<animal.getName()<<" says "<<__________________<<"."<<endl;
}
int main()
{
Animal animal;
Speak(animal);
cout<<endl;
Dog d("Lucky");
Speak(d);
cout<<endl;
Cat c("Daisy");
Speak(c);
return 0;
}控制台
调试终端
