3749 - 7-6修改版
定义一个哺乳动物类Mammal,构造函数输出一行"Constructor of Mammal.";析构函数输出一行"Destructor of Mammal."。
再由此派生出狗类Dog,构造函数输出"Constructor of Dog.";析构函数输出一行"Destructor of Dog."。
从键盘输入一个正整数n,创建n个Dog类对象,要求在全部构造函数调用结束之后再自动调用全部析构函数。
Input
Output
Examples
Input
2
Output
Constructor of Mammal. Constructor of Dog. Constructor of Mammal. Constructor of Dog. Destructor of Dog. Destructor of Mammal. Destructor of Dog. Destructor of Mammal.
Solution C++
#include<iostream> using namespace std; class Mammal{ public: Mammal(){ cout<<"Constructor of Mammal."<<endl; } ~Mammal(){ cout<<"Destructor of Mammal."<<endl; } }; class Dog:public Mammal{ public: Dog(){ cout<<"Constructor of Dog."<<endl; } ~Dog(){ cout<<"Destructor of Dog."<<endl; } }; int main(){ int n; cin>>n; Dog *p = new Dog[n]; delete[] p; return 0; }