虛函數和多態(析構函數)

 

描述

1.定義一個類Animal,該類中包含數據成員name用來記錄動物的名字,並有一個虛函數show用於顯示動物的種類。

2.定義兩個類Cat和Dog,都繼承自Animal;包含show函數,不但要顯示動物的種類(類型分別 爲 cat,dog),還要顯示動物的名字。  

3.定義一個Tiger類,繼承自Cat,包含show函數,顯示動物的種類(類型爲tiger)和名字。

編寫主函數,在主函數中定義一個基類指針,並用這個指針指向派生類的對象,通過基類指針調用派生類的show函數,實現運行時的多態

 

輸入

Cat類,Dog類和Tiger類對象的名字

輸出

Cat類,Dog類和Tiger類對象的類型和名字

樣例輸入

Tom
Sunny
Petter

樣例輸出

This is a cat, and my name is Tom.
This is a dog, and my name is Sunny.
This is a tiger, and my name is Petter.
#pragma GCC optimize(2)
#include <iostream>
#include <string>
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
using namespace std;
class Animal
{
private:
    string name;
public:
    Animal(string name){this->name=name;}
    virtual void show()=0;
    void show_name(){cout<<", and my name is "<<name<<"."<<endl;}
    virtual ~Animal(){//cout<<"delete animal"<<endl;}
};
class Cat:public Animal
{
private:
    string kind;
public:
    Cat(string name,string kind):Animal(name){this->kind=kind;}
    void show(){
        cout<<"This is a "<<kind;
        show_name();
    }
    ~Cat(){//cout<<"delete cat"<<endl;}
};
class Dog:public Animal
{
private:
    string kind;
public:
    Dog(string name,string kind):Animal(name),kind(kind){}
    void show(){
        cout<<"This is a "<<kind;
        show_name();
    }
    ~Dog(){//cout<<"delete dog"<<endl;}
};
class Tiger:public Cat
{
public:
    Tiger(string name,string kind):Cat(name,kind){}
    ~Tiger(){//cout<<"delete tiger"<<endl;}
};
int32_t main()
{
    IOS;
    Animal *p;
    string a,b,c; cin>>a>>b>>c;
    Cat cat(a,"cat");
    Dog dog(b,"dog");
    Tiger tiger(c,"tiger");
    p=&cat; p->show();
    p=&dog; p->show();
    p=&tiger; p->show();
    return 0;
}

定義基類虛析構函數,基類指針派生類對象也可以進行析構。

也就是說,根據上述程序,只需要在基類animal中定義一個虛析構函數,那麼animal的派生類都會依次調用析構函數,直至基類animal析構完成

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章