http://blog.csdn/wangtie_123/article/details/9629111


c++ 里面 如果你写

[cpp]  view plain  copy
  1. char *af ="bbbb";  

会看到 Conversion from string literal to 'char *' is deprecated  翻译后是:从字符串‘char *’转换是废弃的。

这是什么原因呢,书上是这么写的:

c++从c语言继承下来的一种通用结构是c风格字符串,char 字符串字面值就是这中类型的实例,而字符串字面值的类型是const char 类型的数组,是以空字符null结束的字符数组

[cpp]  view plain  copy
  1. char ca1[] = "hello";//正确 包换null  
  2. char ca2[] = {'h','e','l','l','o'};//不含null  
  3. char ca3[] = {'h','e','l','l','o','\0'};//包含null  

代码可以看出,ca1和ca3是属于c风格字符串。

现在回到问题中,那么正确的写法是什么呢?

[cpp]  view plain  copy
  1. char af[] = "hello";  
[cpp]  view plain  copy
  1. char const *af = "hello";  
以上两种方式都是正确的,而为什么要加上const, 因为char字符串字面值是不允许修改的,原因如下:

[cpp]  view plain  copy
  1. char const *ak ="ffff";  
  2. ak = "hello";  
ok,编译正确,这里并木有修改*ak的值,而是把ak重新指向了“hello”

[cpp]  view plain  copy
  1. char const *ak ="ffff";  
  2.  *ak = "h";  
编译有错误 “Read-only variable is  not assignable”

更多推荐

c++ 警告 warning: conversion from string literal to 'char *' is depreca