使用花括号和冒号符号实例化对象

7

Can you please explain the following object instantiation ? How it is called ?

Where can I find more information about this kind of object instantiation ?

#include <string>
#include <iostream>

using namespace std;

class Car {

public:
    string name;
    int wheels;
};

int main() {

    Car c{
        name: "vw",
        wheels: 4
    };

    return 0;
}

I am using GCC with the following options:

$ g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.4.0-1ubuntu1~18.04.1' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1


5
你有一款可以编译这个的编译器吗?如果有,它是什么? - Bathsheba
1
@Bathsheba GCC和Clang都可以使用:https://godbolt.org/z/DEucTZ (尽管不带“-pedantic-errors”) - walnut
1个回答

13

这被称为指定初始化器,但它正在使用过时的语法1。这是C语言的一个特性,在C++20中部分实现。

什么是指定初始化器?

name: "vw"

在这个上下文中,意味着用值“vw”初始化成员name。代码的非过时版本将是:
Car c{
    .name = "vw",
    .wheels = 4
};

GCC还允许您使用C版本的指定初始化器(Designated Initializers),作为语言的扩展,这种方式更加强大。
参见:GCC 6.29 Designated Initializers

3
问题中的语法既不是C++20的语法,也不是用于指定初始化器的C语法,是吗?它似乎是一些GNU特定的语法。 - walnut
我发现自从GCC 2.5以来,这种语法已经过时了。不过看起来他们仍然允许使用它。 - Fred Larson
1
@FredLarson,如果不添加-pedantic标志,GCC似乎不会发出警告。然而,Clang会。请参见我在问题下面链接的godbolt。 - walnut
1
name: value 语法也是 GCC 的扩展,标准 C 和标准 C++ 只允许使用 .name = value - M.M
我已经更新了我的问题,包括C++编译器版本。谢谢大家! - EmmanuelT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接