构造函数初始化

转载: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;
}

初始化的顺序是从父类开始,按照定义的顺序进行,和对象的构造顺序一致;都是从父类到子类。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蒙蒂锅巴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值