Home > Enterprise >  error: passing 'const Player' as 'this' argument discards qualifiers [-fpermissi
error: passing 'const Player' as 'this' argument discards qualifiers [-fpermissi

Time:05-24

I am doing a school project on C and I have an interface defined so I can't change the parameters and types of functions. I am having a problem with this error: error: passing 'const Player' as 'this' argument discards qualifiers [-fpermissive]. I read other questions on stackoverflow about this, but they didn't seem to work. There are 2 classes in this problem. Player extends Character and has abilities. There should be a function that adds abilities to the vector array:

Player& addAbility(const Ability& ability){
    abilities.push_back(ability);

    return *this;
}

The function type and arguments cannot be changed.

After that, there should be a function to get all the abilities:

const vector<Ability>& getAbilities(){
    return abilities;
}

The Ability class looks like this:

class Ability{
public:
    Ability(const string& _name, const float _damage){
        name = _name;
        damage = _damage;
    }
    float getDamage(){
        return damage;
    }

    void setDamage(const float _damage){
        damage = _damage;
    }

    const string& getName(){
        return name;
    }

    void setName(const string& _name){
        name = _name;
    }

private:
    string name;
    float damage;

};

The function type and arguments cannot be changed.

In the class PlayerHelper there should be a function to sum up all the damage of the abilities:

static float getTotalPlayerDamage(const Player& player){
    float sum = 0;
    const vector<Ability>& abilities = player.getAbilities();
    
    for(int i=0;i<abilities.size();i  ){
        sum  = abilities[i].getDamage();
    }

    return sum;
}

The error is on this line:

const vector<Ability>& abilities = player.getAbilities();

I tried const_cast but it didn't seem to work either. Any help would be greatly appreciated!

CodePudding user response:

The problem is that player is a const Player& but getAbilities is a non-const member function and thus cannot be called on a const Player.

To solve this, you can make getAbilities a const member function as shown below:

//------------------------------------vvvvv---->const added here
const vector<Ability>& getAbilities() const{
    return abilities;
}

  •  Tags:  
  • c
  • Related