C++中的语义差异,定义了一个常量数据实例

A_M*_*tar 3 c++ syntax c++11

在初始化常量数据成员时,以下四种不同的语法是否做同样的事情,例如,在C++ 11中是int类型?如果没有,有什么区别?

{
    const int a = 5; //usual initialization, "=" is not assignment operator here it is an initialization operator.
}
{
    const int a(5); //calling the constructor function directly
}
{
    const int a = {5}; //similar to initializing an array
}
{
    const int a{5}; //it should work, but visual studio does not recognizing it
}
Run Code Online (Sandbox Code Playgroud)

为什么第四个不被Visual Studio识别为有效语句?

Dre*_*ann 7

它们在Visual Studio 2013中都是有效且相同的(最后一个在VS2012中无效,如@remyabel建议的那样).

{...}在为类型调用构造函数时,这两种语法可能与其他语法不同,但类型不int 使用构造函数.

在构建一个接受a的类时,它们会有所不同std::initializer_list<T>.

举例来说,这个构造函数以某种形式 - 一直是其中的一部分 std::vector

explicit vector( size_type count ... );
Run Code Online (Sandbox Code Playgroud)

这是在C++ 11中添加的

vector( std::initializer_list<T> init, const Allocator& alloc = Allocator() );
Run Code Online (Sandbox Code Playgroud)

在这里,vector<int>(5)将调用第一个构造函数并使向量大小为5.

并且vector<int>{5}将调用第二个,使单一的载体5.

  • @ v.oddou初始化规则管理不同类型的对象,包括类类型.`int`不是类类型. (2认同)