在构造函数中初始化字段 - 初始化列表与构造函数主体 [英] Initializing fields in constructor - initializer list vs constructor body

查看:37
本文介绍了在构造函数中初始化字段 - 初始化列表与构造函数主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 C++ 已经有一段时间了,但我不确定

I have been working in c++ for some time now, but I am unsure about the difference between

public : Thing(int _foo, int _bar): member1(_foo), member2(_bar){}

public : Thing(int _foo, int _bar){
    member1 = _foo;
    member2 = _bar;
}

我感觉它们做同样的事情,但这两种语法之间是否存在实际差异.其中一个比另一个更安全吗,它们是否以不同的方式处理默认参数.

I have a feeling that they do the same thing, but is there a practical difference between these 2 syntaxes. Is one of these safer then the other, and do they handle default parameters differently.

对第一个例子不太习惯,所以如果我犯了错误,我道歉.

Not totally accustomed to the first example so if I made a mistake on it I apologize.

推荐答案

如果 member1member2 是非 POD(即非Plain Old Data) 类型:

They are not the same if member1 and member2 are non-POD (i.e. non-Plain Old Data) types:

public : Thing(int _foo, int _bar){
    member1 = _foo;
    member2 = _bar;
}

相当于

public : Thing(int _foo, int _bar) : member1(), member2(){
    member1 = _foo;
    member2 = _bar;
}

因为它们会在构造函数体开始执行之前被初始化,所以基本上完​​成了两倍的工作.这也意味着,如果这些成员的类型没有默认构造函数,那么您的代码将不会编译.

because they will be initialized before the constructor body starts executing, so basically twice the work is done. That also means, if the type of these members don't have default constructor, then your code will not compile.

这篇关于在构造函数中初始化字段 - 初始化列表与构造函数主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆