C++ 在向某些继承树类引入附加接口时避免代码重复
c++ avoid code duplication when introducing additional interface to some classes of inheritance tree
下面是一个模型示例。假设我有具有三个坐标 x,y,z 的类 Creature
。我也有继承树:
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()
这样的附加接口不会引入新的数据成员,只会引入新的成员函数。但它使用Creature
类的成员数据z
。
我认为奇怪地重复出现的模板模式 将是一种方式...这样
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); };
相关文章:
- 私钥解密代码使用公共接口说明符到 BSAFE 库 v6.0?
- 在多个头文件中从接口声明被覆盖的函数时,如何避免重复代码?
- 异步接口托管 - > 非托管代码
- 与第三方公共图书馆/代码接口
- 我们可以在层次结构中创建多个纯虚拟接口及其实现而不会代码爆炸吗?
- 可以在没有MATLAB安装的情况下执行C 到MATLAB代码接口
- IMMDevice::激活缺少接口的返回代码
- C++ 在向某些继承树类引入附加接口时避免代码重复
- 通过SWIG禁用python-c 接口的隐式类型检查代码
- 在继承的接口中调用自定义代码
- Simulink Coder语言 - 如何将外部代码与模型接口
- 虚拟HID(人接口设备)的代码示例
- 在RTTI代码中使用非RTTI接口
- 将C 节俭代码汇编为接口Cassandra会导致以下错误.我们在这里缺少什么
- 将C++代码与Python接口的最佳方式是什么
- 如何编写代码以与 Windows Phone 8.1 上的天线接口
- C++代码Firebreath,Serial Port,JavaScript接口
- 隐藏代码以选择接口类的派生类
- 使用SWIG将C++代码与perl接口
- 当使用JNI在现有C++代码中进行移植时,请使用C或C++与JAVA进行接口