C++ 已弃用从字符串常量到“char*"的转换

时间:2022-11-26
本文介绍了C++ 已弃用从字符串常量到“char*"的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 private char str[256];

为此我有一个显式构造函数:

and for it I have an explicit constructor:

explicit myClass(const char *func)
{
    strcpy(str,func);
}

我称之为:

myClass obj("example");

当我编译它时,我收到以下警告:

When I compile this I get the following warning:

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

deprecated conversion from string constant to 'char*'

为什么会这样?

推荐答案

当您遇到以下情况时,您会看到一条错误消息:

This is an error message you see whenever you have a situation like the following:

char* pointer_to_nonconst = "string literal";

为什么?好吧,C 和 C++ 在字符串文字的类型上有所不同.在 C 中,类型是字符数组,而在 C++ 中,它是 constant 字符数组.在任何情况下,都不允许更改字符串字面量的字符,因此 C++ 中的 const 并不是真正的限制,而是更多的类型安全.出于安全原因,如果没有显式转换,从 const char*char* 的转换通常是不可能的.但是为了与 C 向后兼容,C++ 语言仍然允许将字符串文字分配给 char* 并警告您此转换已被弃用.

Why? Well, C and C++ differ in the type of the string literal. In C the type is array of char and in C++ it is constant array of char. In any case, you are not allowed to change the characters of the string literal, so the const in C++ is not really a restriction but more of a type safety thing. A conversion from const char* to char* is generally not possible without an explicit cast for safety reasons. But for backwards compatibility with C the language C++ still allows assigning a string literal to a char* and gives you a warning about this conversion being deprecated.

因此,为了 const 的正确性,您在程序中的某处缺少一个或多个 const .但是您向我们展示的代码不是问题,因为它没有进行这种已弃用的转换.警告一定来自其他地方.

So, somewhere you are missing one or more consts in your program for const correctness. But the code you showed to us is not the problem as it does not do this kind of deprecated conversion. The warning must have come from some other place.

这篇关于C++ 已弃用从字符串常量到“char*"的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:从 C++ 中的 std::string 中删除空格 下一篇:libc++ 中短字符串优化的机制是什么?

相关文章

最新文章