事实证明 char c[] = {"a"};
在 C++03 中都是完全有效的。和 C++11 .
我不希望它是,因为它是 char
的数组而不是 char const*
,我希望大括号初始化器需要兼容为其每个“项目”键入。它有一个项目,这是一个 char const*
而不是 char
。
那么是什么让这个初始化有效呢?这样做有什么理由吗?
类似地,char c[] = {"aa"};
会编译,并且打印 c
会导致输出 "aa
”。
我会当然希望 char c[]{"a"}
在 C++11 中有效,但它不一样!同样,char c[] = {'a'}
在两者中都很明显,char c[] = "a"
也是如此。
最佳答案
虽然它可能不一定是直观的,但它只是是允许的;这两个标准都有一个明确的规则:
[2003: 8.5.2/1]:
Achar
array (whether plainchar
,signed char
, orunsigned char
) can be initialized by a string-literal (optionally enclosed in braces); awchar_t
array can be initialized by a wide string-literal (optionally enclosed in braces); successive characters of the string-literal initialize the members of the array. [..]
[n3290: 8.5.2/1]:
A char array (whetherplain char
,signed char
, orunsigned char
),char16_t
array,char32_t
array, orwchar_t
array can be initialized by a narrow character literal,char16_t
string literal,char32_t
string literal, or wide string literal, respectively, or by an appropriately-typed string literal enclosed in braces. Successive characters of the value of the string literal initialize the elements of the array.
不过,我无法解释为什么委员会会这样做。
关于c++ - 为什么包含字符串文字的初始化程序对初始化 `char` 数组有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8064616/