izumi_tan 2016-06-01 12:50 采纳率: 42.9%
浏览 1152
已采纳

C++基础问题,虚心请教大神

#include< iostream>
using namespace std;
class String
{
public:
String(char *str);
friend bool operator>(String &a, String &b);
void display();
private:
char *p;
};

String::String(char *str)
{
p=str;
}

bool operator>(String &a, String &b)
{
if (strcmp(a.p,b.p)>0)
return true;
else return false;
}

void String::display()
{
cout< < p ;
}
int main()
{String c("life"), d("lifestyle");
cout<<(c>d);

}
为什么会出现warming?
C:\Users\misuzu\Desktop\123\main.cpp|81|warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]|

  • 写回答

3条回答 默认 最新

  • 小灸舞 2016-06-01 13:17
    关注

    用最新的g++编译一下就会得到标题中的警告。
    为什么呢?原来char *背后的含义是:给我个字符串,我要修改它。
    而理论上,我们传给函数的字面常量是没法被修改的。
    所以说,比较和理的办法是把参数类型修改为const char *。
    这个类型说背后的含义是:给我个字符串,我只要读取它。

     #include< iostream>
    using namespace std;
    class String
    {
    public:
        String(const char *str);
        friend bool operator>(String &a, String &b);
        void display();
    private:
        const char *p;
    };
    
    String::String(const char *str)
    {
        p=str;
    }
    
    bool operator>(String &a, String &b)
    {
        if (strcmp(a.p,b.p)>0)
            return true;
        else return false;
    }
    
    
    void String::display()
    {
        cout<<  p   ;
    }
    int main()
    {
        String c("life"), d("lifestyle");
    cout<<(c>d);
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。