C++学习笔记之构造函数(二)初始化列表

类成员变量的初始化方式有两种:1.初始化列表  2.构造函数的函数体中赋值

1)对于普通的数据成员(如int、char、指针等)

class Animal

{

  private:

    double m_weight;

    double m_height;

  public:

    Animal(int weight,int height):m_weight(weight),m_height(height) //构造函数1,使用初始化列表进行初始化

    {

    }

    Animal(int weight,int height) //构造函数2,在函数体内赋值

    {

      m_weight = weight;

      m_height = height;

    }

};

对于普通的数据成员,构造函数1和构造函数2的方式基本没有什么差异,但是一个类中1、2只能出现一个。

对于const类型和&引用类型的数据成员,其初始化必须使用初始化列表的方式进行初始化。

2)无默认构造函数的继承关系中

class Parent

{

  private:

    m_weight;

    m_height;

  public:

    Parent(int weight,int height):m_weight(weight),m_height(height)

    {

    }

};

 

class Child:public Parent

{

  private:

    m_type;

  public:

    Child(int weight,int height,int type)

    {

    }

}

这是如果定义 Parent *p = new Child(10,2,0);编译器会报错,因为子类Child在初始化时会先进行父类Parent的初始化,但是Child的构造函数没有给父类传递参数,那么正常的话应该是会调用Parent的默认构造函数,但是上一篇讲到了,一旦程序员定义了构造函数,那么编译器不在会自动生成默认构造函数,所以这时编译器会提示错误“Parent没有合适的构造函数”。

解决方法:

1.给父类显式的定义一个无参的默认构造函数

Parent()

{

}

2.Child类通过初始化列表传递参数给Parent

Child(int weight,int height,int type):Parent(weight,height)

{

}

posted @ 2018-03-31 00:11  Mr.jason冯  阅读(167)  评论(0)    收藏  举报