c++ - Using += operator with float values -
i'm trying implement operator function solve next error :
error: assignment of member 'animal::weight' in read-only object weight +=amount*(0.02f);
my animal.cpp function looks like:
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 (short version):
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);
then implemented += operator.
float operator+=(const float &weight,const float &amount);
which included in .cpp file:
animal & operator +=(animal &animal, float amount){ float w = animal.getweight(); animal.setweight(w+amount); }
i worked reference weight update every animal. can call function feed, , when want know result function:
float getweight() const {return weight;};
but reason catch next error :
'float operator+=(const float&, const float&)' must have argument of class or enumerated type float operator+=(const float &weight,const float &amount);
any solutions this?
for use feed function have problem. have farm.cpp class loop animals in farm.
void farm::feedallanimals(float amount) { (auto : animals) { if(an != nullptr) { an->feed(amount); } } std::cout << "all animals fed " << amount << "kg of fodder"; }
and in .h file have functions :
public: void feedallanimals(float amount); private: std::vector<std::shared_ptr<const animal>> animals;
my error:
error: passing 'const animal' 'this' argument of 'float animal::feed(float)' discards qualifiers [-fpermissive] an->feed(amount); ^
you declared function feed const member function
void feed(float amount) const; ^^^^^
you may not change object if constant object.
as operator
float operator+=(const float &weight,const float &amount);
then may not overload operators fundamental types. think mean either following
animal & operator +=( animal &animal, float amount);
for example
animal & operator +=( animal &animal, float amount) { animal.setweight( animal.getweight() + amount ); return animal; }
or operator declared member function within class like
animal & operator +=( float amount );
as vector template parameter must without qualifier const if going change objects pointed elements of evctor
std::vector<std::shared_ptr<animal>> animals;
Comments
Post a Comment