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