C ++弃用从字符串常量到'char *'的转换 [英] C++ deprecated conversion from string constant to 'char*'

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

问题描述

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

显式构造函数:

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*'

为什么会发生这种情况? / p>

Why is this happening?

推荐答案

这是您在遇到以下情况时看到的错误讯息:

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

char* pointer_to_nonconst = "string literal";

为什么?嗯,C和C ++的字符串字面量的类型不同。在C中,类型是char的数组,而在C ++中,它是char的常数数组。在任何情况下,你不允许改变字符串字符的字符,所以在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 s的const正确性。但是你向我们展示的代码不是问题,因为它不会做这种弃用的转换。警告必须来自其他地方。

So, somwehere 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 *'的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆