1. 程式人生 > >類的繼承—派生類的函式呼叫分析

類的繼承—派生類的函式呼叫分析

題目:定義一個基類BaseClass,有整型成員變數Number,構造其派生類DerivedClass,觀察建構函式和解構函式的執行情況。
程式碼如下:

/*定義一個基類BaseClass,有整型成員變數Number,構造其派生類DerivedClass,觀察建構函式和解構函式的執行情況。*/
#include <iostream>
using namespace std;
//以下是類的宣告
class baseclass
{
public:
	int number;
	int getage()
	{
		return i1;
	}
	baseclass()
	{
		cout<<
"baseclass類的預設建構函式\n";i1=0; cout<<"i1:"<<getage()<<endl; } baseclass(int i,int j) { cout<<"baseclass類的有參建構函式\n";i1=i; cout<<"i1:"<<getage()<<endl; } baseclass(baseclass&b1) { cout<<"baseclass類的拷貝建構函式\n";i1=b1.i1; cout<<"i1:"<<
getage()<<endl; } ~baseclass() { cout<<"baseclass類的解構函式\n";} private: int i1; }; class derivedclass:public baseclass { public: derivedclass() { cout<<"derivedclass類的預設建構函式\n";i2=0; cout<<"i2:"<<getage()<<endl; } derivedclass(int i,int j):baseclass(i,j)
{ cout<<"derivedclass類的有參建構函式\n";i2=j; cout<<"i2:"<<getage()<<endl; } derivedclass(derivedclass&d1):baseclass(d1) { cout<<"derivedclass類的拷貝建構函式\n";i2=d1.i2; cout<<"i2:"<<getage()<<endl; } ~derivedclass() { cout<<"derivedclass類的解構函式\n";} private: int i2; }; int main() { derivedclass D; derivedclass D2=D; derivedclass D3(1,3); return 0; }