生活随笔
收集整理的這篇文章主要介紹了
C++类中成员变量的初始化有两种方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C++類中成員變量的初始化有兩種方式:
???????? 構造函數初始化列表和構造函數體內賦值。下面看看兩種方式有何不同。
???????? 成員變量初始化的順序是按照在那種定義的順序。
1、內部數據類型(char,int……指針等)
[cpp] view plaincopy
class?Animal??{??public:??????Animal(int?weight,int?height):???????????????m_weight(weight),????????m_height(height)??????{??????}??????Animal(int?weight,int?height)?????????????{??????????m_weight?=?weight;??????????m_height?=?height;??????}??private:??????int?m_weight;??????int?m_height;??};??對于這些內部類型來說,基本上是沒有區別的,效率上也不存在多大差異。
當然A和B方式不能共存的。
?
2、無默認構造函數的繼承關系中
[cpp] view plaincopy
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)?????????{??????}??private:??????int?m_type;??};??上面的子類和父類編譯會出錯:
因為子類Dog初始化之前要進行父類Animal的初始化,但是根據Dog的構造函數,沒有給父類傳遞參數,使用了父類Animal的無參數構造函數。而父類Animal提供了有參數的構造函數,這樣編譯器就不會給父類Animal提供一個默認的無參數的構造函數了,所以編譯時報錯,說找不到合適的默認構造函數可用。要么提供一個無參數的構造函數,要么在子類的Dog的初始化列表中給父類Animal傳遞初始化參數,如下:
[cpp] view plaincopy
class?Dog:?public?Animal??{??public:??????Dog(int?weight,int?height,int?type):??????????Animal(weight,height)???????????????{??????????;??????}??private:??????int?m_type;??};???
3、類中const常量,必須在初始化列表中初始,不能使用賦值的方式初始化
[cpp] view plaincopy
class?Dog:?public?Animal??{??public:??????Dog(int?weight,int?height,int?type):??????????Animal(weight,height),???????????LEGS(4)??????????????????????{????????????????}??private:??????int?m_type;??????const?int?LEGS;??};??4、包含有自定義數據類型(類)對象的成員初始化????????
[cpp] view plaincopy
class?Food??{??public:??????Food(int?type?=?10)??????{??????????m_type?=?10;??????}??????Food(Food?&other)???????????????????????{??????????m_type?=?other.m_type;??????}??????Food?&?operator?=(Food?&other)????????????{??????????m_type?=?other.m_type;??????????return?*this;??????}??private:??????int?m_type;??};????(1)構造函數賦值方式?初始化成員對象m_food??class?Dog:?public?Animal??{??public:??????Dog(Food?&food)??????????????{??????????m_food?=?food;?????????????????????}??private:??????Food?m_food;??};????Food?fd;??Dog?dog(fd);?????Dog?dog(fd);結果:??先執行了???對象類型構造函數Food(int?type?=?10)——>???然后在執行?對象類型構造函數Food?&?operator?=(Food?&other)??想象是為什么?????(2)構造函數初始化列表方式??class?Dog:?public?Animal??{??public:??????Dog(Food?&food)????????:m_food(food)????????????????????????{????????????????}??private:??????Food?m_food;??};????Food?fd;??Dog?dog(fd);?????Dog?dog(fd);結果:執行Food(Food?&other)拷貝構造函數完成初始化??不同的初始化方式得到不同的結果:
明顯構造函數初始化列表的方式得到更高的效率。
原文轉載自點擊打開鏈接
總結
以上是生活随笔為你收集整理的C++类中成员变量的初始化有两种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。