deprecated conversion from string constant to #39;char*#39;(不推荐将字符串常量转换为 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*'
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
