转载:https://blog.csdn.net/qq_16445683/article/details/48517639
1、构造函数初始化列表和构造函数体内赋值
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;
};
4、类中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;
};
聚合初始化方法
struct B{
int i;
std::string str;
};
struct D: public B{
double d;
};
int main(){
D a{}; //使用0初始化所有元素。
D b{{100}}; //如同 {{100,''}, 0}
D c{{}, 1}; //如同 {{0,''}, 1}
D d; //基本类型的值未指定
std::cout << "D a{} : " << a.i << " " << a.str << " " << a.d << std::endl;
std::cout << "D b{{100}} : " << b.i << " " << b.str << " " << b.d << std::endl;
std::cout << "D c{{}, 1} : " << c.i << " " << c.str << " " << c.d << std::endl;
std::cout << "D d : " << d.i << " " << d.str << " " << d.d << std::endl;
return 0;
}
初始化的顺序是从父类开始,按照定义的顺序进行,和对象的构造顺序一致;都是从父类到子类。