简体   繁体   English

使用new时的数组初始化

[英]Array initialization when using new

In C# I could do this: 在C#中,我可以这样做:

char[] a = new char[] {'a', 'a', 'a'};

But can I do something like that in C++? 但我可以在C ++中做类似的事情吗? I tried: 我试过了:

char *a = new char [] {'a', 'a', 'a'};

But it doesn't compile. 但它没有编译。

why not just do this? 为什么不这样做呢? :

char a[] = {'a', 'a', 'a'};

Also avoid using arrays completely. 还要避免完全使用数组。 Use std::vector 使用std::vector

This is a bug in the C++ spec (which doesn't let this simple construct to compile). 这是C ++规范中的一个错误(它不允许这个简单的构造进行编译)。 You need to supply the size 你需要提供尺寸

char *a = new char [3] {'a', 'a', 'a'};

See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1469 . http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1469 Note that if you parenthesize the type name it is a type-id and not a new-type-id and hence syntactically allows you to omit the size expression. 请注意,如果您使用类型名称括号,则它是type-id而不是new-type-id ,因此在语法上允许您省略size表达式。 So you may be able to find an implementation that allows you to say 所以你可以找到一个允许你说的实现

char *a = new (char[]){'a', 'a', 'a'};

Althought it is clear that it wasn't the explicit intent that this is possible (and some rules in the new paragraphs can be interpreted to forbid it). 虽然很明显,这可能不是明确的意图(并且new段落中的某些规则可以被解释为禁止它)。

You probably don't want to use an array in C++. 您可能不想在C ++中使用数组。 Use a std::vector instead. 请改用std::vector

You can even initialise it to 3 'a's. 您甚至可以将其初始化为3'a'。

std::vector<char> vectorOfChars(3, 'a');

If your compiler supports C++11, you can even use an initialiser list. 如果您的编译器支持C ++ 11,您甚至可以使用初始化列表。

std::vector<char> vectorOfChars{'a', 'a', 'a'};

我想你想要的是这个:

   const char a[] = {'a', 'a', 'a'};

Yes, you can do it like; 是的,你可以这样做;

char a[] = {'a', 'a', 'a'};

Check out Arrays (C++) from MSDN . 查看来自MSDN的 Arrays (C++)

string a = "aaa"; string a =“aaa”; a[0] , a[1] ..etc This will be much easier if you wanna make 2-D arrays of string..etc a [0],a [1] ..等等如果你想制作二维数组的字符串,这将会容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM