繼承引出的對構造方法的要求

繼承引出的對構造方法的要求

構造方法是類的一個特殊成員,它會在實例化對象時被自動調用。咱們沒法使用對象來調用構造函數,由於在構造函數構造出對象以前,對象是不存在的。所以構造函數被用來建立對象,而不能經過對象來調用。c++

那麼咱們都知道繼承,繼承因爲派生類繼承基類內成員(沒法繼承構造方法,繼承了私有成員,只是沒法直接訪問),我派生類能夠調用基類的成員,那麼我派生類確定要知道基類是如何對本身數據進行初始化的。那麼這提出了第一個要求。函數

  • 派生類必定會調用基類的構造方法。

以C++代碼爲例,假設咱們如今有兩個類,基類Person,派生類Student設計

class Person {
public:
    // constructor with argument
	Person(int x) {
		cout << "Person Constructor with " << x << endl;
	}
};

class Student:public Person {
public:	
    // default constructor without argument
	Student() {
		cout << "Student Default Constructor" << endl;
	}

};

int main (){
    Student a;
}

咱們看上面的代碼,基類沒有無參構造方法,派生類有。咱們知道主函數中 Student a 這行代碼會隱性調用Student類中默認的無參構造方法。同時,剛剛學到的,也確定會調用基類Person中的構造方法。可是,這裏的代碼沒有指定會調用基類哪個構造方法,因此就會調用基類Person默認的無參構造方法。code

但是,基類Person沒有無參構造方法啊!!!因此這個程序編譯器的確會報錯,這也就提出了下一個要求。對象

  • 必定要設計至少2個構造方法,包含1個有參數的構造方法用於初始化成員變量和1個無參數的構造方法設定默認狀況。

因而,咱們修改代碼,繼承

class Person {
public:
    // default constructor
	Person() {
		cout << "Person Default Constructor" << endl;
	}
	// constructor with argument
	Person(int x) {
		cout << "Person Constructor with " << x << endl;
	}
};

class Student:public Person {
public:	
    // default constructor
	Student() {
		cout << "Student Default Constructor" << endl;
	}
	// constructor with argument
	Student(int y)  {
		cout << "Student Constructor with " << y << endl;
	}

};

int main(){
	Student a;
	
	return 0;
}

/*
Output
Person Default Constructor
Student Default Constructor
*/

這樣,程序就正常運行了。因爲咱們是調用了派生類的默認無參構造方法,一樣也調用了基類的無參構造方法。編譯器

咱們能夠看到,是先調用了基類的構造方法再調用了派生類的構造方法,符合人們的認知。或者你能夠這麼想,我是我父母的孩子,我身上的DNA來自於他們,我不得先知道他們的DNA是啥才行嗎?因此建立派生類對象時會先調用基類的構造方法。it

那麼問題來了,個人派生類的構造方法,想顯式地調用基類別的構造方法,能夠嗎?編譯

固然是能夠的。class

class Person {
public:
	Person() {
		cout << "Person Default Constructor" << endl;
	}

	Person(int x) {
		cout << "Person Constructor with " << x << endl;
	}
};

class Student:public Person {
public:	
    // 調用父類中帶參的構造方法
	Student() : Person(10) {
		cout << "Student Default Constructor" << endl;
	}

    // 一樣調用父類中帶參的構造方法
	Student(int y) : Person(y) {
		cout << "Student Constructor with " << y << endl;
	}

};


int main(){
	Student a(20);
	
	return 0;
}

/*
Output
Person Constructor with 20
Student Constructor with 20

*/
  • 派生類能夠指定調用指定的基類構造方法。若是基類的構造方法是無參的,那麼在派生類中寫不寫均可以,不寫的話會隱式地調用。
相關文章
相關標籤/搜索