問題描述
我有一個帶有 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 const
s 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模板網!