2012-02-08 73 views
0

我与C字符串玩弄++,我不明白为什么下面的编译时将导致错误:+ =在C++字符串

string s = "hi"; 
s += " " + "there!"; 

错误消息:

error: invalid operands of types ‘const char [2]’ and ‘const char [6]’ to binary ‘operator+’ 

我也试过s+= (" " + "there!");,它也不起作用。

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

+5

告诉我们错误信息,或者它没有发生。 – 2012-02-08 23:57:20

+2

这对某些现有答案是隐含的,但值得一提的是,C++优先规则意味着“+”there!“'在s + ='操作之前被评估,所以你也尝试过的括号没有被'没有任何区别。有趣的是,'s + =“”“there!”'会起作用 - 相邻字符串的连接是在编译的早期阶段完成的,而's = s +“”+“there!”'也可以作为s +“”'首先被评估,然后它的'std :: string'结果有“there!”添加 - 当'+'的任一参数是一个'std :: string'时它工作得很好...... – 2012-02-09 00:38:17

+0

+1谢谢Tony提供这些细节! – 2012-02-09 00:47:20

回答

9

问题是你试图“添加”两个文字字符串。文字字符串在C++中不是std :: string类型,它们就像不可变的字符数组。将两个加在一起并不合理,因为它将像添加两个指针一样。

你可以,但是,这样做:

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

这是因为在C++中定义来连接C++字符串使用C字符串的方法。

+0

“s = s +”“+”在那里!“;”工作,然后呢?是“s +”“”执行,导致std :: string,然后“+”那里“”部分完成,再次针对std :: string? a + = b和a = a + b之间的技术差异是什么? – 2014-12-16 13:11:43

+0

's +“there”'因为'string + const char *'有一个重载操作符。在C++中'a + = b'和'a = a + b'通常没有什么区别,但是一个库实现者如果他们是邪恶的话可能会有所不同。 – 2014-12-17 00:07:01

9

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

s += string(" ") + "there!"; 

你也可以通过将它们彼此相邻而不+串连文字。

s += " " "there!"; 
1

当我尝试它,我得到:

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; 
}