简体   繁体   中英

How to deal with "not covariant" errors in paired hierarchies (C++)

Suppose I want a class Team to have a virtual get_player member which is implemented by FootballTeam and RugbyTeam , and that these implementations return the covariant types FootballPlayer and RugbyPlayer .

Suppose I also want Player to have a virtual get_team member which is implemented by FootballPlayer and RugbyPlayer , and that these implementations return the covariant types FootballTeam and RugbyTeam .

Is it possible to implement this pattern? I've tried, but, when overriding the get_player member of Team , I'm getting the error: "Return type of virtual function 'get_player' is not covariant with the return type of the function it overrides".

I can't define the Player hierarchy first, because then I'd have the same problem but the other way around!

class Player;
class FootballPlayer;
class RugbyPlayer;

class Team {
  virtual Player &get_player() = 0;
};
class FootballTeam : public Team {
  FootballPlayer &get_player() override; // error here
};
class RugbyTeam : public Team {
  RugbyPlayer &get_player() override; // error here
};

class Player {
  virtual Team& get_team() = 0;
};
class FootballPlayer : public Player {
  FootballTeam& get_team() override;
};
class RugbyPlayer : public Player {
  RugbyTeam& get_team() override;
};

We, unfortunately, cannot forward declare classes WITH inheritance.

So you have to drop one covariant return type and break the circular dependency loop somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM