You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
在建構 non-derived class 物件時,建構子只需要擔心自身的成員,但如果是 derived class 的話,情況比較複雜,首先是 derived class 物件建構的流程:
分配一塊足夠空間的記憶體
呼叫適當的建構子
Base class 物件會先被建構出來,如果沒有指定,會直接用預設建構子
Initialization list 初始化變數
執行建構子的 body block
返還控制權給 caller
若需要設定 base class 的成員可以在 derived class 建構子的 body 中設定,但如果有成員是 const,這個方法並不能用,C++ 提供另一個方法來初始化 base class 的成員,可以在 initialization list 中指定 constructor of base class。:
classDerived: publicBase {
public:double m_cost;
Derived(double cost = 0.0, int id = 0) : Base(id), // call Base(int) constructor with value idm_cost(cost) {}
// ...
};
The text was updated successfully, but these errors were encountered:
Constructors and initialization of derived classes
Base and Derived class:
在建構 non-derived class 物件時,建構子只需要擔心自身的成員,但如果是 derived class 的話,情況比較複雜,首先是 derived class 物件建構的流程:
若需要設定 base class 的成員可以在 derived class 建構子的 body 中設定,但如果有成員是
const
,這個方法並不能用,C++ 提供另一個方法來初始化 base class 的成員,可以在 initialization list 中指定 constructor of base class。:The text was updated successfully, but these errors were encountered: