Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/163.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++中玩字符串,我不明白为什么编译时会导致错误: string s = "hi"; s += " " + "there!";_C++_String - Fatal编程技术网

+;=用C++; 我在C++中玩字符串,我不明白为什么编译时会导致错误: string s = "hi"; s += " " + "there!";

+;=用C++; 我在C++中玩字符串,我不明白为什么编译时会导致错误: string s = "hi"; s += " " + "there!";,c++,string,C++,String,错误消息: error: invalid operands of types ‘const char [2]’ and ‘const char [6]’ to binary ‘operator+’ 我还尝试了s++=(“+”那里!”)并且它也不起作用 为什么我不能使用二进制运算符+=以这种方式连接字符串?问题是您试图“添加”两个文本字符串。文字字符串不是C++中的STD::string类型,它们就像是不可变的字符数组。将两个指针相加没有意义,因为这就像将两个指针相加一样 但是,您可以执行以下操

错误消息:

error: invalid operands of types ‘const char [2]’ and ‘const char [6]’ to binary ‘operator+’
我还尝试了
s++=(“+”那里!”)并且它也不起作用


为什么我不能使用二进制运算符
+=
以这种方式连接字符串?

问题是您试图“添加”两个文本字符串。文字字符串不是C++中的STD::string类型,它们就像是不可变的字符数组。将两个指针相加没有意义,因为这就像将两个指针相加一样

但是,您可以执行以下操作:

std::string("foo") + "bar"

这是因为C++中有方法将C++字符串与C字符串串联起来。

字符串不是字符串对象,它们只是字符数组。当您尝试这样添加它们时,它们会衰减为指向数组的指针,而您无法添加一对指针。如果将第一个文本转换为字符串对象,它将按预期工作

s += string(" ") + "there!";
您也可以通过将文字彼此相邻而不使用
+
来连接文字

s += " "  "there!";
当我尝试时,我得到:

632 $ g++ foo.C
foo.C: In function ‘int main()’:
foo.C:5:16: error: invalid operands of types ‘const char [2]’ and ‘const char [7]’ to binary ‘operator+’
这说明“”是常量字符数组,而不是字符串

这项工作:

636 $ cat foo.C
#include <string>
using std::string;
int main(void){
    string s = "hi";
    s += string(" ") + string("there!");
    return 0;
}
636$cat foo.C
#包括
使用std::string;
内部主(空){
字符串s=“hi”;
s+=string(“”+string(“那里!”);
返回0;
}

告诉我们错误消息,或者它没有发生。它是隐含的一些现有的答案,但值得一提的是C++优先规则意味着<代码>“+”!“”是在<代码> S+= < /C>操作之前评估的,所以您尝试的括号也没有任何区别。有趣的是,
s+=“there!”
将起作用-相邻字符串文本的串联在编译的早期阶段完成,并且
s=s++“there!”
也将起作用,因为首先计算
s+”
,然后其
std::string
结果为“there!”添加-当
+
的任一参数是
std::string
时,它工作正常….+1感谢Tony提供这些详细信息!“s=s+”“+”在那里是什么意思!“那么,工作?是否正在执行“s+”,从而生成std::string,然后针对std::string完成“+”there”部分?a+=b和a=a+b之间的技术区别是什么?
s+“there”
之所以有效,是因为
string+const char*
有一个重载运算符。在C++中,<>代码> A++B和 A+A+B通常没有区别,但是库实现者如果它们是邪恶的,则会有一些不同。