問題描述
我有一個(gè)帶有 private char str[256];
為此我有一個(gè)顯式構(gòu)造函數(shù):
and for it I have an explicit constructor:
explicit myClass(const char *func)
{
strcpy(str,func);
}
我稱之為:
myClass obj("example");
當(dāng)我編譯它時(shí),我收到以下警告:
When I compile this I get the following warning:
不推薦將字符串常量轉(zhuǎn)換為 'char*'
deprecated conversion from string constant to 'char*'
為什么會(huì)這樣?
推薦答案
當(dāng)您遇到以下情況時(shí),您會(huì)看到一條錯(cuò)誤消息:
This is an error message you see whenever you have a situation like the following:
char* pointer_to_nonconst = "string literal";
為什么?好吧,C 和 C++ 在字符串文字的類型上有所不同.在 C 中,類型是字符數(shù)組,而在 C++ 中,它是 constant 字符數(shù)組.在任何情況下,都不允許更改字符串字面量的字符,因此 C++ 中的 const 并不是真正的限制,而是更多的類型安全.出于安全原因,如果沒有顯式轉(zhuǎn)換,從 const char*
到 char*
的轉(zhuǎn)換通常是不可能的.但是為了與 C 向后兼容,C++ 語言仍然允許將字符串文字分配給 char*
并警告您此轉(zhuǎn)換已被棄用.
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 的正確性,您在程序中的某處缺少一個(gè)或多個(gè) const
.但是您向我們展示的代碼不是問題,因?yàn)樗鼪]有進(jìn)行這種已棄用的轉(zhuǎn)換.警告一定來自其他地方.
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.
這篇關(guān)于C++ 已棄用從字符串常量到“char*"的轉(zhuǎn)換的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!