不推荐将字符串常量转换为 'char*'

2022-01-12 00:00:00 string char c++

可能重复:
不推荐使用C++从字符串常量到'char*'的转换

我想通过 char* 将字符串传递给函数.

I want to pass a string via char* to a function.

 char *Type = new char[10];
 Type = "Access";  // ERROR

但是我得到了这个错误:

However I get this error:

 error: deprecated conversion from string constant to 'char*'

我该如何解决这个问题?

How can I fix that?

推荐答案

如果真的要修改Type:

If you really want to modify Type:

char *Type = new char[10];
strcpy( Type, "Access" );

如果您不想修改访问权限:

If you don't want to modify access:

const char *Type = "Access";

请注意,然而,C 和 C++ 中的 char 数组会带来很多问题.例如,你真的不知道对 new 的调用是否成功,或者它是否会抛出异常.此外,strcpy() 可能会超过 10 个字符的限制.

Please note, that, however, arrays of char in C and in C++ come with a lot of problems. For example, you don't really know if the call to new has been successful, or whether it is going to throw an exception. Also, strcpy() could surpass the limit of 10 chars.

所以你可以考虑,如果你想稍后修改类型:

So you can consider, if you want to modify type later:

std::string Type = "Access";

如果你不想修改它:

const std::string Type = "Access";

...使用 std::string 的好处是它能够应对所有这些问题.

... the benefit of using std::string is that it is able to cope with all these issues.

相关文章