我试图实现一个运算符函数来解决下一个错误:
error: assignment of member 'Animal::weight' in read-only object weight +=amount*(0.02f);
My 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);
^
答案 0 :(得分:3)
您将函数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 );
对于向量,如果要更改evctor元素指向的对象,则模板参数必须没有限定符const
std::vector<std::shared_ptr<Animal>> animals;