error: const std::string message = "Hello" + ", world" + exclam;

这是我在学《Accelerated C++》时遇到的问题。

error

:
invalid operands of types
`
const

char
[
6
]
' and `const char[8]'
to binary
`
operator
+
'





程序是:





#include


<iostream>





int

main
()



{


   

const
std
::
string exclam
=

"!"
;


   

const
std
::
string message
=

"Hello"

+

", world"

+
exclam
;


    std

::
cout
<<
message
;


   

return

0
;



}



出错原因是(引自http://stackoverflow.com/questions/2329461/help-a-beginner-with-a-c-hello-world):



Because in C++, string literals (like "Hello" are not of type std::string . They are plain char arrays, or C-style strings.

So for the line const std::string message = "Hello" + ", world" + exclam; ,the types the compiler has to work with are:

const std::string message = const char[6] + const char[8] + std::string;

and given the associativity of + , the operations it has to perform are:

const std::string message = ((const char[6] + const char[8]) + std::string);

That is, the left-most addition must be evaluated first, and the result passed to the rightmost addition.

So the compiler tries to evaluate const char[6] + const char[8] . There is no addition defined for arrays. Arrays are implicitly converted to pointers, but this doesn't help the compiler. That just means it ends up with const char* + const char* , and no addition is defined for pointers either.

At this point, it doesn't know that you want the result to be converted to a std::string .

However, in your second example:

const

std
::
string hello
=

"Hello"
;



const
std
::
string message
=
hello
+

", world"

+

"!"
;




it works, because the operations the compiler would see were std::string + const char[8] + const char[2] . Here, the first addition can be converted to std::string + const char* , and here the addition operator is defined, and returns a std::string . So the compiler has successfully figured out the first addition, and since the result was a string, the second addition looks like this: std::string + const char[2] , and like before, this isn't possible, but the array can be converted to a pointer, and then the compiler is able to find an addition operator that works, again resulting in a std::string .





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值