您的位置:首页 > 其它

warning: deprecated conversion from string constant to ‘char*’

2015-05-08 19:05 253 查看
环境: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐