以下两个程序让我很困惑。在第一个程序中,我使用const char*
,我可以重新分配字符串。在第二个例子中,我使用const char[]
,现在我无法再重新分配字符串。有人可以解释一下这是为什么吗?
#include <iostream>
using namespace std;
const char* x {"one"};
void callthis(const char t[]);
int main()
{
callthis("two");
return 0;
}
void callthis(const char t[]){
t=x; // OK
// OR
// x=t; // OK
}
第二
#include <iostream>
using namespace std;
const char x[] {"three"};
void callthis(const char* t);
int main(){
callthis("four");
return 0;
}
void callthis(const char* t){
x=t; // error: assignment of read-only variable 'x';
// error : incompatible types in assignment of
// 'const char*' to 'const char [6]'
}
答案 0 :(得分:4)
数组不是指针。让我们再次讨论:数组不是指针
无法分配数组。一旦声明如果当时没有初始化,设置数组值的唯一方法是迭代到每个元素并设置其内容。如果我们使用
,阵列上的const
是红色听证会
char x[] {"three"};
//...
void callthis(const char* t){
x=t;
}
我们仍然会收到如下错误:
错误:数组类型&#39; char [6]&#39;不可分配
第一个例子工作的原因是可以指定指针,const char *
不是常量指针,而是指向常量char
的指针。由于指针不是const
,因此可以改变指针指向的内容。如果您要使用
const char * const x {"one"};
然后您收到了
的错误错误:无法分配给变量&#39; x&#39;使用const限定类型&#39; const char * const&#39;
我还注意到您在代码中使用using namespace std;
。在小例子中,它并没有真正伤害任何东西,但你应该养成不使用它的习惯。有关原因的详细信息,请参阅:Why is “using namespace std” in C++ considered bad practice?