通過 Ocelot 實現 API 閘道器
阿新 • • 發佈:2020-09-22
建構函式
-
初始化列表與賦值
C++類中成員變數的初始化有兩種方式:建構函式初始化列表和建構函式體內賦值。
注:列表初始化時成員變數初始化的順序是按照在類中定義的順序。
主要有以下幾種情況:
-
內部資料型別(int, char, 指標等)
兩者初始化方法效率基本沒區別
-
無預設建構函式的繼承關係中
class Animal { public: Animal(int weight,int height): //沒有提供無參的建構函式 m_weight(weight), m_height(height) { } private: int m_weight; int m_height; }; class Dog: public Animal { public: Dog(int weight,int height,int type) //error 建構函式 父類Animal無合適建構函式 { } private: int m_type; };
這種必須在派生類建構函式中初始化提供父類的初始化
class Dog: public Animal { public: Dog(int weight,int height,int type): Animal(weight,height) //必須使用初始化列表增加對父類的初始化 { ; } private: int m_type; };
-
類中const常量,必須在初始化列表中初始,不能使用賦值的方式初始化
-
包含有自定義資料型別(類)物件的成員初始化
建構函式初始化列表的方式得到更高的效率
-