初始化字符串时额外花括号 [英] Extra curly braces while initializing a string

查看:239
本文介绍了初始化字符串时额外花括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据问题此代码的含义是什么,为什么它会工作?我想问下面代码中 s1 s2 之间的区别:

  int main(){
const char * s1 = {Hello}; //奇怪,但工作如下
const char * s2 =Hello; //普通case
return 0;
}

为什么要使用额外花括号?任何对C ++标准的引用将是有用的。

解决方案

在C ++ 98(和C ++ 03) ;在第8.5节中:


14 - 如果 T 是标量类型,声明形式
T x = {a};
相当于
T x = a;


在C ++ 11中,这由列表初始化(8.5.4p3)覆盖:,那么p>

引用类型是引用相关的E,对象或引用从该元素初始化[...]


认为这是与使用大括号初始化标量相同的问题。


According to question What does this code mean and why does it work? I want to ask what difference between s1 and s2 in the code below:

int main() {
    const char* s1 = { "Hello" }; // strange but work as followed
    const char* s2 = "Hello"; // ordinary case 
    return 0;
}

Why extra curly braces are permitted? Any reference to C++ standard will be useful.

解决方案

In C++98 (and C++03) this is pretty simple; in clause 8.5:

14 - If T is a scalar type, then a declaration of the form T x = { a }; is equivalent to T x = a;

In C++11 this is covered by list-initialization (8.5.4p3):

[...] if the initializer list has a single element of type E and either T is not a reference type or its referenced type is reference-related to E, the object or reference is initialized from that element [...]

I think this is the same question as Initializing scalars with braces.

这篇关于初始化字符串时额外花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆