C++ 是否可以使用运算符new和初始化器语法初始化非POD数组?
我刚刚读过并理解了,但这并不能完全解决我的问题 这段代码给了我一个Clang编译错误:C++ 是否可以使用运算符new和初始化器语法初始化非POD数组?,c++,arrays,c++11,clang,initializer-list,C++,Arrays,C++11,Clang,Initializer List,我刚刚读过并理解了,但这并不能完全解决我的问题 这段代码给了我一个Clang编译错误: struct A { A(int first, int second) {} }; void myFunc() { new A[1] {{1, 2}}; } 我希望{1,2}}使用单个元素初始化数组,然后使用构造函数args{1,2}初始化数组,但我得到以下错误: error: no matching constructor for initialization of 'A' new A[
struct A
{
A(int first, int second) {}
};
void myFunc()
{
new A[1] {{1, 2}};
}
我希望{1,2}}使用单个元素初始化数组,然后使用构造函数args{1,2}初始化数组,但我得到以下错误:
error: no matching constructor for initialization of 'A'
new A[1] {{1, 2}};
^
note: candidate constructor not viable: requires 2 arguments, but 0 were provided
A(int first, int second) {}
^
note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
struct A
^
为什么这个语法不起作用呢?这似乎是。声明默认构造函数(使其可访问且不被删除),即使未调用默认构造函数,程序也会编译:
#include <iostream>
struct A
{
A() { std::cout << "huh?\n"; } // or without definition, linker won't complain
A(int first, int second) { std::cout << "works fine?\n"; }
};
int main()
{
new A[1] {{1, 2}};
}
#包括
结构A
{
A(){std::cout是因为A
不接受初始值设定项列表作为其构造函数的唯一参数。{1,2}
是std::初始值设定项列表,(1,2)
是两个独立的参数,它们是非常不同的东西。仅供参考,g++4.9接受此程序。@Arman{1,2}
是一个带括号的init列表。带括号的init列表不必调用初始值设定项\u list
构造函数。带括号的init列表更一般,它们是统一初始化的一部分。