首页 > 解决方案 > 使用大括号和 : 符号的对象实例化

问题描述

你能解释一下下面的对象实例化吗?它是怎么称呼的?

我在哪里可以找到有关这种对象实例化的更多信息?

#include <string>
#include <iostream>

using namespace std;

class Car {

public:
    string name;
    int wheels;
};

int main() {

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

    return 0;
}

我正在使用具有以下选项的 GCC:

$ 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

标签: c++classinitializer

解决方案


这称为指定初始值设定项,但它使用过时的语法1。这是 C++ 在 C++20 中部分实现的 C 功能。

什么

name: "vw"

name在这种情况下意味着用 value初始化成员"vw"。代码的非过时版本将是

Car c{
    .name = "vw",
    .wheels = 4
};

GCC 还将允许您使用“更强大”的指定初始化程序的 C 版本作为语言的扩展。

1见:GCC 6.29 指定初始化器


推荐阅读