【TOJ 5254】C++實驗:繼承中的構造函數和析構函數
阿新 • • 發佈:2018-05-06
des 能夠 con OS esp space AC tom cto
Derived Constructor 0
Derived Destructor 0
Base Destructor 0
Base Destructor 0
描述
實現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; }
【TOJ 5254】C++實驗:繼承中的構造函數和析構函數