const char*vs char*

Kra*_*ken 2 c++ string pointers

这是我的书中所说的:

char *p="Hello"; //pointer is variable, string is constant
*p='M'; // error
p="bye"; // works
Run Code Online (Sandbox Code Playgroud)

好吧,在C中我的第二行不会给我任何错误,在C++中都没有.

我在Windows 7上使用Turbo C++.如果我尝试使用gcc或其他东西,现在是真的.

如果上面的代码被本书正确解释,也在类似的行上,

#include<iostream.h>
void display(char*);
void display(const char*);
void main()
{
char* ch1="hello";
const char *ch2="bye";
display(ch1);
display(ch2);
}

void display(char* p)
{
cout << p << endl;
}

void display(const char* p)
{
cout << p << endl;
}
Run Code Online (Sandbox Code Playgroud)

现在我的书正在考虑char*const char*相同,因为如果是,那么上面的代码将不起作用,因为参数将是相同的?

(虽然我在turbo + windows上得到输出Hello bye.)

哪一个是正确的?

rua*_*akh 6

语言规范不是编译器对您做出的承诺,而是您和编译器都签署的相互合同.(当然是隐喻性的.显然,这不是一个具有法律约束力的合同.)如果你通过写作违反合同*p='M';,那么你已经触发了"未定义的行为",你不能指望编译器有任何特定的行为:也许它将是严格的,并给你一个编译错误,也许它会在运行时变得不稳定...你没有阻止你的讨价还价的结束,而且它允许现在无论它想要什么.另见:http://catb.org/jargon/html/N/nasal-demons.html.