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

deprecated conversion from string constant to #39;char*#39;(不推荐将字符串常量转换为 char*)

本文介绍了不推荐将字符串常量转换为 'char*'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
不推荐使用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.

这篇关于不推荐将字符串常量转换为 'char*'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:不推荐将字符串常量转换为 'char*'

基础教程推荐