Acclerated C++ 第1章

1-1 : 正确

1-2 : 不正确

 std::string exclam = "!";
std::string message = "hello" + ", world" +exclam;错!( error C2110: cannot add twopointers)

std::string message = exclam +"hello" + ", world" ; 正确!

std::string message = "hello" +exclam + ", world" ;正确!

 

1、2题解释:

String类型相+,不是加法运算,实质上是字符串连接。

原来在C++中,字符串常量(像"Hello")不是std::string类型,而是字符数组,或者说是C风格的字符串。

(1)const std::string message = "Hello" + ",world" + exclam;

编译器解释为:const std::string message = ((const char[6] + const char[8]) +std::string);

("+"是左结合性的)

第一个加法:被转化为const char[6] + constchar[8]

但是并没有为数组定义这样的加法(即没有为数组重载加法运算符)。

虽然数组被隐式的转换为指针,但是const char* + const char*也没有为两个指针之间定义加法运算。

编译器并不知道你想把结果转换为std::string类型。

 

(2)const std::string message = exclam  +"Hello" + ",world"

编译器解释为:const std::string message =( std::string +const char[8]) + const char[2]

第一个加法:被转换为 std::string + const char*,这样的一个加法运算是已定义了的,返回类型为 std::string。并且结果是一个字符串

第二个加法:就被转换为 std::string + const char*同上。

======================================================================

 

1-3 : 正确

1-4 : 正确  }} 改成 };} 后没影响

1-5 :不正确 vc6报错: error C2065: 'x' : undeclaredidentifier 

 

3、4、5解释:

(1)在{}内定义的变量只在{}内有效,在其外是无效的。

(2)程序代码段用{}起来表示一个句子。在一个句子后加一个“;”号,仍然是一个句子。

======================================================================

 

1-6 :

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值