简体   繁体   English

C ++使用{}初始化成员变量

[英]C++ initialize member variables with { }

Recently I have seen member variable initialization in c++ as such: 最近,我看到了c ++中的成员变量初始化,如下所示:

class foo
{
public:
    foo();
private:
    bool bar{false};
};

What is the point of variable initialization like this/how does member variable declaration/definition like this differ or not differ from using an initialization list as such: 这样的变量初始化的意义是什么/这样的成员变量声明/定义与这样使用初始化列表有何不同或没有不同:

foo::foo() : bar(false) {}

It's useful when you have a lot of constructors. 当您有很多构造函数时,这很有用。 bool bar{false}; means set bar to false unless the constructor initialises it to something else. 表示将bar设置为false,除非构造函数将其初始化为其他东西。 it's just for convenience 只是为了方便

See http://en.cppreference.com/w/cpp/language/data_members#Member_initialization for a more detailed explanation 有关详细说明,请参见http://en.cppreference.com/w/cpp/language/data_members#Member_initialization

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM