c++ - 对浮点值使用 += 运算符

标签 c++ operator-overloading operators constants shared-ptr

我正在尝试实现一个运算符函数来解决下一个错误:

error: assignment of member 'Animal::weight' in read-only object weight +=amount*(0.02f);

我的 Animal.cpp 函数如下所示:

void Animal::feed(float amount) const
  {
  if (type == "sheep"){
        amount=amount*(0.02f);
        weight+=amount;
  }else if (type == "cow"){
      weight +=amount*(0.05f);
  }else if (type == "pig"){
       weight +=amount*(0.1f);
  }
  return weight;
}

Animal.h(简短版本):

    class Animal
      {
      public:
        Animal(std::string aType, const char *anSex, float aWeight, QDateTime birthday);
        float getWeight() const {return weight;};

        void setWeight(float value) {weight = value;};
        float feed(float amount) const;
        void feedAnimal(float amount);
      private:
        float weight;
      };

float operator+=(const float &weight,const float &amount);

然后我实现了一个 += 运算符。

float operator+=(const float &weight,const float &amount);

这也包含在 .cpp 文件中:

 Animal & operator +=(Animal &animal, float amount){
    float w = animal.getWeight();
    animal.setWeight(w+amount);
    }

我使用了引用资料,以便更新每只动物的体重。所以我可以调用函数 feed,当我想知道结果时,我可以使用 get 函数来实现:

float getWeight() const {return weight;};

但由于某种原因我发现了下一个错误:

 'float operator+=(const float&, const float&)' must have an argument of class or enumerated type
 float operator+=(const float &weight,const float &amount);

有什么解决办法吗?

对于使用 feed 功能我也遇到了问题。我有我的 Farm.cpp 类,我在其中循环农场中的所有动物。

void Farm::feedAllAnimals(float amount)
  {
  for (auto an : animals) {
          if(an != nullptr) {
                 an->feed(amount);
          }
   }
  std::cout << "all animals fed with " << amount << "kg of fodder";
  }

在我的 .h 文件中,我有这些函数:

Public:
    void feedAllAnimals(float amount);

Private: 
std::vector<std::shared_ptr<const Animal>> animals;

我的错误:

error: passing 'const Animal' as 'this' argument of 'float Animal::feed(float)' discards qualifiers [-fpermissive] an->feed(amount);
                             ^

最佳答案

您将函数 feed 声明为 const 成员函数

void feed(float amount) const;
                        ^^^^^

如果该对象是常量对象,则不能更改该对象。

对于运营商

float operator+=(const float &weight,const float &amount);

那么你不能重载基本类型的运算符。 我认为你的意思是以下内容

Animal & operator +=( Animal &animal, float amount);

例如

Animal & operator +=( Animal &animal, float amount)
{
    animal.setWeight( animal.getWeight() + amount );

    return animal;
}

或者在类中声明为成员函数的运算符,例如

Animal & operator +=( float amount );

对于 vector ,如果要更改 evctor 元素指向的对象,则模板参数必须不带限定符 const

std::vector<std::shared_ptr<Animal>> animals;

关于c++ - 对浮点值使用 += 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32036494/

相关文章:

python - 以运算符作为参数的函数

c++ - 如何保证在粘贴之前参数的完整宏扩展?

c++ - 鼠标悬停在 QGraphicsPixmapItem 上后 Qt 显示工具提示

c++ - 为模板类重载 operator[] - C++

c++ - 队列类中的运算符 <<

c++ - cout 对象是否仍然是单个实例,即它永远不会被复制?

android - Android项目中的C++ Firebase链接错误

c++ - 映射 vector 的时间复杂度是多少?

android - 使用MVNO时如何查找运营商名称? (我想要通知栏中写的那个)

python - Python中的模运算符