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)拷貝建構函式完成初始化
不同的初始化方式得到不同的結果:
明顯建構函式初始化列表的方式得到更高的效率。