<分区>
在我的 C++ 类(class)中使用了这种初始化。
char *a = "abcd";
但是,当我使用它时,一个编译器 提示:
a value of type "const char*" cannot by used to initialize an entity of type "char*"
*a 应该是指针。请问有什么问题吗?我使用 Visual Studio 2017
<分区>
在我的 C++ 类(class)中使用了这种初始化。
char *a = "abcd";
但是,当我使用它时,一个编译器 提示:
a value of type "const char*" cannot by used to initialize an entity of type "char*"
*a 应该是指针。请问有什么问题吗?我使用 Visual Studio 2017
最佳答案
你需要指定const
const char *a = "abcd";
原因是字符串 "abcd"
是常量,因此不应分配给非 const 指针。它在旧的 C++ (AFAIK) 中是可以容忍的,但自 C++11 以来,它不是,而带有 /permissive-
的 VS2017 做了正确的事情并禁止了这种不良做法。
关于C++通过指针初始化char数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53364522/