【TOJ 5254】C++实验:继承中的构造函数和析构函数

描述

实现C++类Base和Derived,并编写相关构造函数和析构函数,使其能够输出样例信息。

主函数里的代码已经给出,请补充完整,提交时请勿包含已经给出的代码。

int main()
{
	Base *p = new Derived(1, 2);
	delete p;
	Base b;
	Derived d;
	return 0;
}

输入

输出

输出样例信息。

样例输入

 无

样例输出

Base Constructor 1
Derived Constructor 2
Derived Destructor 2
Base Destructor 1
Base Constructor 0
Base Constructor 0
Derived Constructor 0
Derived Destructor 0
Base Destructor 0
Base Destructor 0

#include<iostream>
using namespace std;
class Base{
    public:
        int x;
        Base(int a=0):x(a)
        {
            x=a;
            cout<<"Base Constructor "<<x<<endl;
        }
        virtual~Base(){cout<<"Base Destructor "<<x<<endl;}
}; 
class Derived:public Base{
    public:
        int y;
        Derived(int a=0,int b=0):Base(a),y(b)
        {
            cout<<"Derived Constructor "<<y<<endl;
        }
        ~Derived()
        {
            cout<<"Derived Destructor "<<y<<endl;
        }
};
int main()
{
    Base *p = new Derived(1, 2);
    delete p;
    Base b;
    Derived d;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/kannyi/p/8999466.html