Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 常量char*和char*_C++_Char_Constants - Fatal编程技术网

C++ 常量char*和char*

C++ 常量char*和char*,c++,char,constants,C++,Char,Constants,我明白 char *s = "Hello World!" ; 存储在只读内存中,不能通过指针修改字符串文字 这和 const char *s = "Hello World!"; 也是“字符串”字符*或常量字符*的类型 通过将类型指定为const char*,更难意外覆盖内存,因为如果您尝试以下操作,编译器将给出错误: const char *s = "Hello World!"; s[0] = 'X'; // compile error 如果不使用const,则问题可能在运行时才会被

我明白

char *s = "Hello World!" ; 
存储在只读内存中,不能通过指针修改字符串文字

这和

const char *s = "Hello World!"; 

也是“字符串”字符*或常量字符*的类型

通过将类型指定为
const char*
,更难意外覆盖内存,因为如果您尝试以下操作,编译器将给出错误:

const char *s = "Hello World!";
s[0] = 'X';  // compile error

如果不使用const,则问题可能在运行时才会被发现,或者可能只是导致程序出现细微错误。

区别在于后者是合法的,前者不是。这是在C++11中所做的更改。形式上,
“Hello World!”
的类型为
常量字符[13]
;它可以转换为
常量字符*
。在过去,它的类型可以是
char[13]
,可以转换为
char*
。C++通过添加<代码> const 更改了数组的类型,但将转换保持到 char */COD> >,因此使用C++代码> char *<代码>的C代码将在C++中工作,但修改指针指向的文本产生了未定义的行为。C++11删除了对
char*
的转换,因此现在您只能合法地进行转换

const char *s = "Hello world!";

第一种方法是不推荐的,而且很危险。哦,是的,我看到尝试修改char*s可以成功编译,但是const char*s不能。因此,基本上,将const作为一个红旗来不改变字符串。酷<代码>C++11删除了对字符的转换*——不在gcc48中。这是gcc错误吗?@LeonidVolnitsky-在C++11中不允许转换。规则是编译器必须对违反约束的情况发出诊断,该约束没有说明“无需诊断”。因此,所需要的只是一个诊断,有时是一个警告。如果添加
const
会改变类型,那么
const
const
不是更有逻辑吗?