0

In C++, I'm trying to understand why you don't get an error when you construct a string like this:

const string hello = "Hello";
const string message = hello + ", world" + "!";

But you do get a compile time error with this:

const string exclam = "!";
const string msg =  "Hello" + ", world" + exclam

Compile time error is:

main.cpp:10:33: error: invalid operands of types ‘const char [6]’ and 
‘const char [8]’ to binary ‘operator+’

Why is the first run fine but the second produce a compile time Error?

4

1 回答 1

7

如果你把它写出来会更有意义:

hello + ", world" + "!";看起来像这样:

operator+(operator+(hello, ", world"), "!");

尽管

"Hello" + ", world" + exclam看起来像这样

operator+(operator+("Hello" , ", world"), exclam);

由于没有operator+需要两个const char数组,因此代码失败。

但是,不需要一个,因为您可以像下面这样连接它们(注意我刚刚删除了+符号):

const string msg =  "Hello" ", world" + exclam
于 2013-09-14T03:31:04.687 回答