为什么我不能new像这样使用运算符:
char* p;
p = new char('a')[3];
delete[] p;
Run Code Online (Sandbox Code Playgroud)
编译说:
error C2143: syntax error : missing ';' before '['
error C3409: empty attribute block is not allowed
error C2143: syntax error : missing ']' before 'constant'
Run Code Online (Sandbox Code Playgroud)
在C++ 11中,您可以通过新的统一初始化初始化动态分配的聚合:
p = new char[3] {'a', 'a', 'a'};
Run Code Online (Sandbox Code Playgroud)
在C++ 98中,您无法为动态分配的聚合指定初始化列表.你所能做的就是首先分配数组,然后用一个值填充它:
p = new char[3];
std::fill(p, p + 3, 'a');
Run Code Online (Sandbox Code Playgroud)
在C++ 11中,您可以说:
char * p = new char[3] { 'a', 'a', 'a' };
Run Code Online (Sandbox Code Playgroud)
在11之前,没有办法初始化动态数组而不是零(或默认).在这种情况下,您可以使用std::fill:
#include <algorithm>
std::fill(p, p + 3, 'a');
Run Code Online (Sandbox Code Playgroud)