以下是一个模型示例。假设我有一个Creature类,它具有三个坐标x,y,z。我也有继承树:

class Creature {
  int x;
  int y;
  int z;
};
class Mammal : public Creature {common code for mammals};
class Wolf : public Mammal;
class Bat : public Mammal;
class Birds : public Creature {common code for birds};
class Penguin : public Bird;
class Crow : public Bird;

一些生物可以飞行,因此它们应该具有以下成员函数(所有生物的实现都相同):
void fly(int height) {z = height;}

因此,我执行以下操作:
class FlyingMammal : public Mammal {
  void fly(int height) {z = height;}
  //'z' is also used in some methods of non-flying creatures,
  //so it can't be moved to FlyingMammal class.
};
class Wolf : public Mammal;
class Bat : public FlyingMammal;
class FlyingBird : public Bird {
  void fly(int height) {z = height;}
};
class Penguin : public Bird;
class Crow : public FlyingBird;

但是,我在FlyingMammal和FlyingBird中有代码重复。有避免的标准模式吗?我想某种多重继承可能适合这里,但不知道该怎么做。

请注意,像fly()这样的附加接口(interface)不会引入新的数据成员,而只会引入新的成员函数。但是它使用z类的成员数据Creature

最佳答案

我认为Curiously recurring template pattern将是其中一种...

template <typename TThisClass>
class Flier
{
public:
    void fly(int z) { static_cast<TThisClass *>(this)->setZ(z); }
};

class Creature {
private:
  int x;
  int y;
  int z;
public:
  void setX(int x) { this->x = x; }
  void setY(int y) { this->y = y; }
  void setZ(int z) { this->z = z; }
  // add setter & getter for x, y, z
};

class Mammal : public Creature { /*common code for mammals*/};

class Wolf : public Mammal { };

class Bat : public Mammal, public Flier<Bat> { };

class Bird : public Creature { /*common code for birds*/ };

class Penguin : public Bird { };

class Crow : public Bird, public Flier<Crow> { };

int main(int, char **) { Crow c; c.fly(1000); };

关于c++ - 引入一些继承树类的其他接口(interface)时,c++避免代码重复,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42878447/

10-09 06:11