環境:Linux Ubuntu 下用g++ 編譯 C++檔案(windows下應該同樣)
警告提示:warning: deprecated conversion from string constant to ‘char*’
大緻意思:不接受被轉換的字元串為常量字元串
還原代碼:
#include<iostream>
using namespace std;
void F(char *s)
{
cout<<s<<endl;
}
int main()
{
F("hellow");
return 0;
}
原因:因為函數F的形參原型為char *s,表示傳遞一個字元串的位址過來,并且可以通過傳遞過來的位址來修改其中的值;而上述代碼中,F("hellow")傳遞的是一個常量,不能被修改,故編譯器會警告。
解決方法:
法1: F的形參改為const char *s,因為有const修飾符,變代表指針s指向的值不能被修改,符合F("hellow")不能被改變的特性;
法2: 先定義一個char型的數組變量(char str[10]="hellow"),調用函數F時用str作為參數即F(str),這樣str中的值是可以被改變的,符合F(char *s)的特性;
若想同時實作這兩種方法,重載即可。
#include<iostream>
using namespace std;
void F(const char *s)
{
cout<<s<<endl;
}
void F(char *s)
{
cout<<s<<endl;
}
int main()
{
char str[10]="world";
F("hellow");
F(str);
return 0;
}
轉載于:https://www.cnblogs.com/tolic/p/7142268.html