【问题标题】:Error: passing 'const SunscreenSPF' as 'this' argument discards qualifiers issue错误:将“const SunscreenSPF”作为“this”参数传递会丢弃限定符问题
【发布时间】:2021-03-23 04:40:04
【问题描述】:

我正在计算一个人在使用屏幕保护膜的情况下可以晒伤多长时间。由于我喜欢使用不同的方法来做事,我创建了一个名为 SunscreenSPF 的类。

class SunscreenSPF
{
private:
    string skinColor;
    int SPF;
    int time;

public:
    SunscreenSPF(string skinColor, int SPF, int time)
    {
        this->skinColor=skinColor;
        this->SPF=SPF;
        this->time=time;
    }

    int calculateTime ()
    {
        return SPF*time;
    }

    friend ostream& operator<<(ostream &os, const SunscreenSPF &data)
    {
        os<<"Skin Color = "<<data.skinColor<<endl
          <<"Time outdoors = "<<data.time<<endl
          <<"SPF Level = "<<data.SPF<<endl
          <<"Time to get sunburn with protection = "<<data.calculateTime()<<endl;
    }
};

我收到此错误:将“const SunscreenSPF”作为“this”参数传递会丢弃限定符 [-fpermissive]|

我该如何解决这个问题?

【问题讨论】:

  • 你需要从operator&lt;&lt;函数返回os,否则你会遇到警告。

标签: c++ class


【解决方案1】:

在函数friend ostream&amp; operator&lt;&lt;(ostream &amp;os, const SunscreenSPF &amp;data) 中,data 有一个const 限定符。但是当calculateTime()被调用时,这个成员方法不提供不修改data对象的保证。将const 限定符添加到您的calculateTime() 函数中

int calculateTime () const
{
    return SPF*time;
}

【讨论】:

    猜你喜欢
    • 2021-11-10
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    相关资源
    最近更新 更多