C++-warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]-给char* 形参 传入 宏定义字符串

#include <iostream>
using namespace std;

int fuc(char *a)
{
    cout << a << endl;
}
int main()
{
    fuc("hello");
}

如果编译器版本比较高,会提示warning: ISO C++11 does not allow conversion from string literal to 'char *'

 

为什么呢?原来char *背后的含义是:给我个字符串,我要修改它。

而理论上,我们传给函数的字面常量是没法被修改的

所以说,比较和理的办法是把参数类型修改为const char *

这个类型说背后的含义是:给我个字符串,我只要读取它。

如何同时接收const类型和非const类型?重载

#include <iostream>
using  namespace  std;
 
int  fuc( char  *a)
{
     cout << a << endl;
}
int  fuc( const  char  *a)
{
     cout << a << endl;
}
int  main()
{
     char  a[] =  "hello 123" ;
     fuc(a);
     const  char  b[] =  "hello 123" ;
     fuc(a);
}

 

#include <iostream>
using namespace std;

int fuc(char *a)
{
    cout << a << endl;
}
int main()
{
    fuc("hello");
}
posted @ 2020-11-26 15:13  不明白就去明白  阅读(539)  评论(0编辑  收藏  举报