C++派生類的構造函數與析構函數

存個代碼

#include <bits/stdc++.h>
using namespace std;
class Parent {
protected:
	int pnum;
public:
	Parent(){
		pnum = 0;
		cout << "調用Parent的無參構造函數" << endl;
	}
	Parent(int pnum) {
		this->pnum = pnum;
		cout << "調用Parent的有參構造函數" << endl;
	}
	~Parent() {
		cout << "調用Parent的析構函數" << endl;
	}
	void show() {
		cout << pnum << endl;
	}
};
class Child : public Parent {
protected:
	int cnum;
public:
	Child() : Parent() {
		pnum = 0;
		cnum = 0;
		cout << "調用Child的無參構造函數" << endl;
	}
	Child(int pnum, int cnum) : Parent(pnum) {
		this->cnum = cnum;
		cout << "調用Child的有參構造函數" << endl;
	}
	~Child() {
		cout << "調用Child的析構函數" << endl;
	}
	void show() {
		cout << pnum << ' ' << cnum << endl;
	}
};
class B {
public:
	int bnum;
	B() {
		bnum = 0;
		cout << "調用B的無參構造函數" << endl;
	}
	B(int bnum) {
		this->bnum = bnum;
		cout << "調用B的有參構造函數" << endl;
	}
	~B() {
		cout << "調用B的析構函數" << endl;
	}
	void show() {
		cout << bnum << endl;
	}
};
class A : public Parent {
private:
	int anum;
	B b; // A類中定義了B類的對象 
public:
	A() : Parent(), b() {
		pnum = 0;
		b.bnum = 0;
		anum = 0;
		cout << "調用A的無參構造函數" << endl;
	}
	A(int pnum, int bnum, int anum) : Parent(pnum), b(bnum) {
		this->anum = anum;
		cout << "調用A的有參構造函數" << endl;
	}
	~A() {
		cout << "調用A的析構函數" << endl;
	}
	void show() {
		cout << pnum << ' ' << b.bnum << ' ' << anum << endl;
	}
};
int main() {
	Parent p1;
	Parent p2(5);
	p1.show();
	p2.show();
	
	cout << "****************" << endl;
	
	Child c1;
	Child c2(1, 2);
	c1.show();
	c2.show();
	
	cout << "****************" << endl;
	
	B b1;
	B b2(10);
	b1.show();
	b2.show();
	
	cout << "****************" << endl;
	
	A a1;
	A a2(5, 6, 7);
	a1.show();
	a2.show();
	return 0;
}

結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章