【问题标题】:passing reference to constant object while the object is not updated [duplicate]在对象未更新时传递对常量对象的引用[重复]
【发布时间】:2021-05-25 10:46:35
【问题描述】:

我在下面写了一个玩具类。

标题

class saleData{
  private:
    std::string isbn;
    unsigned cnt;
    double price;

  public:
    saleData(const std::string s, unsigned c, double p): isbn{s}, cnt{c}, price{p} {};
    
    unsigned getCnt(){
      return cnt;
    }

    double getPrice(){
      return price;
    }

    saleData &combine(####const#### saleData &x){
      cnt += x.getCnt();
      price=(price*cnt + x.getCnt()*x.getPrice()) / (cnt + x.getCnt());
      return *this;
    }
};

主函数

int main(){
  saleData x("xx", 3, 4.4);
  saleData y("yy", 4, 3.3);
  x.combine(y);
  cout<<"total revenue is "<<x.getCnt() * x.getPrice()<<endl;
  return 0;
}

如果我在组合函数中有那个####const####,我会得到一些编译错误,比如

sale_data.h:25:35: error: passing 'const saleData' as 'this' argument of 'unsigned int 
saleData::getCnt()' discards qualifiers [-fpermissive] 
       price=(price*cnt + x.getCnt()*x.getPrice()) / (cnt + x.getCnt());

如果我删除 const,一切正常。

但我没有为 saleData x 修改任何内容,对吧?我只是在看它的cnt和价格。

【问题讨论】:

  • 记住这是一个编译器错误。编译器正在分析您的代码是否存在可能的 const 违规,而不是运行您的代码以查看它们是否发生。当您在像 y 这样的 const 对象上调用像 getPrice 这样的非 const 方法时,会发生一个 const 违规。

标签: c++ constants pass-by-reference


【解决方案1】:

不能在 const 对象上调用非 const 成员函数(getPrice()getCnt())。您应该将它们设为const,以告知它们不会修改任何非静态数据成员。

class saleData{
  private:
    std::string isbn;
    unsigned cnt;
    double price;

  public:
    saleData(const std::string s, unsigned c, double p): isbn{s}, cnt{c}, price{p} {};
    
    unsigned getCnt() const {
      return cnt;
    }

    double getPrice() const {
      return price;
    }

    saleData &combine(const saleData &x){
      cnt += x.getCnt();
      price=(price*cnt + x.getCnt()*x.getPrice()) / (cnt + x.getCnt());
      return *this;
    }
};

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 2016-11-08
    • 2021-08-19
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 2015-05-10
    • 1970-01-01
    相关资源
    最近更新 更多