如何处理配对层次结构中的 "not covariant" 错误 (C++)

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

假设我想让 class Team 有一个由 FootballTeamRugbyTeam 实现的虚拟 get_player 成员,并且这些实现 return 协变类型 FootballPlayerRugbyPlayer.

假设我还希望 Player 有一个由 FootballPlayerRugbyPlayer 实现的虚拟 get_team 成员,并且这些实现 return协变类型 FootballTeamRugbyTeam.

这个模式可以实现吗?我试过了,但是,当重写 Teamget_player 成员时,我收到错误消息:“Return 类型的虚函数 'get_player' 与return 它覆盖的函数类型。

我不能先定义 Player 层次结构,因为那样我会遇到同样的问题,但反过来!

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;
};

不幸的是,我们无法向前声明 类 WITH 继承。

所以你必须删除一个协变 return 类型并在某处打破循环依赖循环。