c++ - 如何在 C++ 中使用括号语法初始化 POD 数组?

标签 c++ c++11

到目前为止,我只看到了 C++ 中 POD 数组的赋值初始化。例如,

int array[]={1,2,3};

来自 here我了解到,当数组位于 C++11 的类/结构中时,可以使用初始化列表方法对其进行初始化。但是我尝试像这样定义数组:

int array[]({1,2,3});

编译时出现错误:

array initializer must be an initializer list

我认为它只需要进行一些修改,但我就是想不通。您能告诉我如何实现吗?

顺便说一句,复制构造函数比这里的赋值构造函数更有效吗?我猜不是,但我不知道确切的答案。

最佳答案

POD 数组不能使用类似构造函数(括号)的语法进行初始化。如果要以统一的方式初始化变量,请使用初始化列表(花括号)语法来初始化变量。例如,以下代码将使用 gcc 4.7.3 进行编译:

struct Foo
{
    Foo(int a, std::string s);
}

int main()
{
    // can also use parentheses on the next two lines
    int a{3};
    Foo f{a, "A string"};

    // only curly braces can be used here
    int arr[]{4, 5, 6};

    return 0;
}

花括号语法还允许您使用 std::initializer_list 以与数组相同的方式构造 vector 和其他 STL 类型,这只有在括号中才有可能,如下所示:

std::vector<int> v{1, 2, 3, 4, 5};

// contrast with

std::initializer_list<int> i{1, 2, 3, 4, 5}; // must use curly braces here
std::vector<int> v(i);

关于c++ - 如何在 C++ 中使用括号语法初始化 POD 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17381002/

相关文章:

c++ - typeinfo name() 和 endl 在 Windows 和 mingw 中不能一起工作

c++ - C++ 中 'x % y != 0' 的机制

c++ - unique_ptr : can't get value from iterator 的无序映射

multithreading - 使用 boost::lockfree::spsc_queue 时需要内存屏障吗?

c++ - 'override' 限定符与尾随返回类型一起去哪里?

c++ - 带有 boost 变体递归包装器的字符串解析器

C++ 和 OpenCV : clustering white pixels algorithm

c++ - 静态对象声明只导致没有错误

c++ - 返回对临时 C++ 的引用

c++ - 当基类不是时,为什么派生类可以 move 构造?