Possible Duplicate:
C++ deprecated conversion from string constant to 'char*'
我想通过 char* 将字符串传递给函数。
char *Type = new char[10];
Type = "Access"; // ERROR
但是我得到了这个错误:
error: deprecated conversion from string constant to 'char*'
我该如何解决这个问题?
最佳答案
如果真的要修改Type:
char *Type = new char[10];
strcpy( Type, "Access" );
如果您不想修改访问权限:
const char *Type = "Access";
请注意,然而,C 和 C++ 中的 char 数组会带来很多问题。例如,你真的不知道对 new 的调用是否成功,或者它是否会抛出异常。此外,strcpy() 可能会超过 10 个字符的限制。
所以你可以考虑,如果你想稍后修改类型:
std::string Type = "Access";
如果你不想修改它:
const std::string Type = "Access";
...使用 std::string
的好处是它能够应对所有这些问题。
关于c++ - 不推荐从字符串常量到 'char*' 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8126512/