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

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

问题描述

我一直在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){}

p>

and

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.

推荐答案

如果 member1 member2 是非POD类型:

They are not the same if member1 and member2 are non-POD 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天全站免登陆