繼承中的構造析構原則

  • 1、子類對象在創建時會首先調用父類的構造函數
  • 2、父類構造函數執行結束後,執行子類的構造函數
  • 3、當父類的構造函數有參數時,需要在子類的初始化列表中顯示調用
  • 4、析構函數調用的先後順序與構造函數相反
#include <iostream>
using namespace std;
// 先調用父類構造函數  然後再調用子類的構造函數
// 先調用子類的析構函數, 然後再調用父類的析構函數
class Parent {
public:
	Parent(int a,int b)
	{
		cout << "Parent構造函數" << endl;
		this->a = a;
		this->b = b;
	}
	~Parent()
	{
		cout << "Parent析構函數" << endl;
	}
	void printP()
	{
		cout << "parent" << endl;
	}
private:
	int a, b;
};

class Child :public Parent 
{
public:
	
	Child(int c, int a, int b): Parent(a, b)
	{
		cout << "Child構造函數" << endl;
		this->c = c;
	}
	~Child()
	{
		cout << "Child析構函數" << endl;
	}
	void printC()
	{
		cout << "child" << endl;
	}
private:
	int c;
};

void display()
{
	Child c1(1, 2, 3);
}


int main()
{
	// Parent p(1, 2);
	display();
	system("pause");
	return 1;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章