Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c+中字符串上的加号运算符+; 你能解释一下从加速C++中练习1-2吗?_C++_String - Fatal编程技术网

c+中字符串上的加号运算符+; 你能解释一下从加速C++中练习1-2吗?

c+中字符串上的加号运算符+; 你能解释一下从加速C++中练习1-2吗?,c++,string,C++,String,int main() { const std::string exclam = "!"; const std::string message = "Hello" + ", world" + exclam; std::cout << message << std::endl; } intmain() { 常量std::字符串感叹号=“!”; const std::string message=“Hello”+,world”+感叹号; std::co

int main()
{
    const std::string exclam = "!";
    const std::string message = "Hello" + ", world" + exclam;
    std::cout << message << std::endl;
}
intmain()
{
常量std::字符串感叹号=“!”;
const std::string message=“Hello”+,world”+感叹号;
std::cout操作符+
从左到右。然后
的“Hello”+,world”+感叹号被解释为
(“Hello”+,world”)+感叹号
,而
的“Hello”+,world”
无效。
的“Hello”
,world”
常量字符[]
s,并可能衰减为指针
const char*
,无法添加

使用
std::string
代替c样式字符串,或者将代码更改为
“Hello”+(“,world”+感叹号)
可以工作,因为有一个可以接受两个
std::string
或一个
std::string
和一个c样式字符串(作为第一个或第二个操作数),并返回可以进一步添加的
std::string

运算符+
的从左到右。然后
“Hello”+,world“+感叹号”
被解释为
(“Hello”+,world”)+感叹号
,而
“Hello”+,world”
无效。
“Hello”
,world”
const char[]
s,可以作为
const char*
衰减到指针,无法添加


使用
std::string
代替c样式字符串,或者将代码更改为
“Hello”+(“,world”+感叹号)
可以工作,因为有一个可以接受两个
std::string
或一个
std::string
和一个c样式字符串(作为第一个或第二个操作数),并返回可以进一步添加的
std::string

添加到的说明中,您可以使用
std::string
+
运算符执行此操作:

const std::string left  = "Hello ";
const std::string right = "World";
const std::string point = "!";
std::cout << left + right + point << std::endl;
或者使用
printf
功能(别忘了
#包括
):


如果您想知道
c_str()
是关于什么的,请查看此图。

添加到的解释中,您可以通过使用
std::string的
+
运算符来执行此操作:

const std::string left  = "Hello ";
const std::string right = "World";
const std::string point = "!";
std::cout << left + right + point << std::endl;
或者使用
printf
功能(别忘了
#包括
):


如果你想知道
c_str()
是关于什么的,请看这个。

不,因为它是左关联的。不,因为它是左关联的。
const std::string left  = "Hello";
const std::string right = "World";
const std::string point = "!";
printf("%s %s%s\n", left.c_str(), right.c_str(), point.c_str());