C++建構函式初始化列表與賦值

來源:互聯網
上載者:User


C++類中成員變數的初始化有兩種方式:

         建構函式初始化列表和建構函式體內賦值。下面看看兩種方式有何不同。

         成員變數初始化的順序是按照在那種定義的順序。

1 內部資料類型(char,int……指標等)

class Animal
{
public:
Animal(int weight,int height): //A初始化列表
m_weight(weight),
m_height(height)
{
}
Animal(int weight,int height) //B函數體內初始化
{
m_weight = weight;
m_height = height;
}
private:
int m_weight;
int m_height;
};

對於這些內部類型來說,基本上是沒有區別的,效率上也不存在多大差異。

當然A和B方式不能共存的。


 

2 無預設建構函式的繼承關係中

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;
};


 

3 類中const常量,必須在初始化列表中初始,不能使用賦值的方式初始化

 

class Dog: public Animal
{
public:
Dog(int weight,int height,int type):
Animal(weight,height),
LEGS(4) //必須在初始化列表中初始化
{
//LEGS = 4; //error
}
private:
int m_type;
const int LEGS;
};


4 包含有自訂資料類型(類)對象的成員初始化        

 

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)
{
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) //初始化 成員對象
{
//m_food = food;
}
private:
Food m_food;
};
//使用
Food fd;
Dog dog(fd); //
Dog dog(fd);結果:執行Food(Food &other)拷貝建構函式完成初始化


不同的初始化方式得到不同的結果:

      明顯建構函式初始化列表的方式得到更高的效率。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.