欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

动物园(虚函数与多态)------已解决

程序员文章站 2024-03-21 11:48:16
...

动物园(虚函数与多态)------已解决问题:未释放内存

#include <iostream>  
#include <string>  
using namespace std;  
   
class Animal  
{  
public:  
    Animal() {}  
    virtual void Speak() {};  
	virtual ~Animal(){}
};  
   
class Tiger : public Animal  
{  
private:  
     string type, name;  
     int age;  
   
public:  
    Tiger(string type_val, string name_val, int age_val)  
    {  
        type = type_val;  
        name = name_val;  
        age = age_val;  
    }  
   
    virtual void Speak()  
    {  
        cout << "Hello,I am " << name << ",AOOO." << endl;  
    }  
    ~Tiger(){}  
};  
class Pig : public Animal  
{  
private:  
     string type, name;  
     int age;  
   
public:  
    Pig(string type_val, string name_val, int age_val)  
    {  
        type = type_val;  
        name = name_val;  
        age = age_val;  
    }  
    virtual void Speak()  
    {  
        cout << "Hello,I am " << name << ",HENGHENG." << endl;  
    }  
    ~Pig(){}  
};  
   
class Dog : public Animal  
{  
private:  
     string type, name;  
     int age;  
   
public:  
    Dog(string type_val, string name_val, int age_val)  
    {  
        type = type_val;  
        name = name_val;  
        age = age_val;  
    }  
    virtual void Speak()  
    {  
        cout << "Hello,I am " << name << ",WangWang." << endl;  
    }  
    ~Dog(){}  
};  
class Duck : public Animal  
{  
private:  
     string type, name;  
     int age;  
   
public:  
    Duck(string type_val, string name_val, int age_val)  
    {  
        type = type_val;  
        name = name_val;  
        age = age_val;  
    }  
    virtual void Speak()  
    {  
        cout << "Hello,I am " << name << ",GAGA." << endl;  
    }  
    ~Duck(){}  
};  
void Speak(Animal *p)  
{  
    p->Speak();  
}  
   
int main()  
{  
    int T;  
    string type, name;  
    int age;  
    cin >> T;  
    while(T--)  
    {  
        cin >> type >> name >> age;  
        if(type == "Tiger")  
        {  
            Tiger *p = new Tiger(type, name, age);  
            Speak(p);  
			delete p;////////
        }  
        else if(type == "Pig")  
        {  
            Pig *p = new Pig(type, name, age);  
            Speak(p);
			delete p;////////
        }  
        else if(type == "Dog" )  
        {  
            Dog *p = new Dog(type, name, age);  
            Speak(p);  
			delete p;////////
        }  
        else if(type == "Duck")  
        {  
            Duck *p = new Duck(type, name, age);  
            Speak(p);  
			delete p;////////
        }  
        else  
        {  
            cout << "There is no " << type << " in our Zoo." << endl;  
        }  
    }  
    return 0;  
}  

样例输入

4
Tiger Jumpjump 10
Pig Piglet 4
Rabbit labi 3
Duck tanglaoya 8

样例输出

Hello,I am Jumpjump,AOOO.
Hello,I am Piglet,HENGHENG.
There is no Rabbit in our Zoo.
Hello,I am tanglaoya,GAGA.

相关标签: 虚函数