[TOJ 5254] C++ Experiment: Constructor and Destructor in Inheritance

describe

Implement C++ classes Base and Derived, and write related constructors and destructors so that they can output sample information.

The code in the main function has been given, please complete it. Please do not include the given code when submitting.

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

enter

without

output

Output sample information.

sample input

 without

Sample output

Base Constructor 1
Derived Constructor 2
Derived Destructor 2
Base Destroyer 1
Base Constructor 0
Base Constructor 0
Derived Constructor 0
Derived Destructor 0
Base Destroyer 0
Base Destroyer 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;
        }
};
intmain ()
{
    Base *p = new Derived(1, 2);
    delete p;
    Base b;
    Derived d;
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325369328&siteId=291194637