c++primer 2/28---string

当进行 string 对象和字符串字面值混合连接操作时,+ 操作符的左右操作数必须至少有一个是 string 类型的:

     string s1 = "hello";   // no punctuation
     string s2 = "world";
     string s3 = s1 + ", ";           // ok: adding a string and a literal
     string s4 = "hello" + ", ";      // error: no string operand
     string s5 = s1 + ", " + "world"; // ok: each + has string operand
     string s6 = "hello" + ", " + s2; // error: can't add string literals

 s4 的初始化试图将两个字符串字面值相加,因此是非法的。s6 的初始化是非法的。依次来看每个子表达式,则第一个子表达式试图把两个字符串字面值连接起来。

虽然任何整型数值都可作为索引,但索引的实际数据类型却是类型 unsigned 类型 string::size_type


sizeof("hello")=6,"hello"是字符串字面值,这是C风格字符串,末尾自动添加结束符\0,sizeof()包含结束符,。strlen();不包含结束符的长度。

string s("hello");s.size=5.是用字符串字面值(包含结束符)为c++类型的字符串对象初始化,初始化的对象中不包含结束符(生成对象的时候自动滤掉了)。并不是s.size()没有把结束符算进来。


Null characters were needed in C 

In c++ you can forget '\0' if you use string class, you just don't need to worry about it.

Null characters were needed in C because if you did something like
char myText[] = "HELLO";
myText would really be a pointer to somewhere in memory, let's say forexample, it's at memory location 100 (which it probably wouldn't be butthat's a nice round number), the memory might really look like
100: HELLO\0askdj7y3hcdm,chy3nc73hjkcz78zxcojczxkj
Without that \0 (null character) there, C wouldn't know whether the string was H, HELLO, HELLOaskdj or anything else.

However, in C++ "strings" are no longer null-terminated because thestring object can store not only what characters make up the string (asC did), but how long it should be, so a C++ string can just say "HELLO"is 5 characters, so start at the pointer and read 5 characters.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值