我正在尝试创建一个同时代表两种不同行为的类。像下面这样:
class IMouse {
public:
virtual void Walk() const = 0;
};
class TSimpleMouse : public IMouse {
public:
void Walk() const;
};
class IBat {
public:
virtual void Fly() const = 0;
};
class TSimpleBat : public IBat {
public:
void Fly() const;
};
template <class TMouse, class TBat>
class TSuperCreatureImpl {
public:
void Do() const {
Walk();
Fly();
}
};
typedef TSuperCreatureImpl<TSimpleMouse, TSimpleBat> TSimpleSuperCreature;
这对我来说很重要,因为我想制作不同的 typedef。看起来很简单。
但我也希望 Fly 和 Walk 方法具有参数(例如速度)。我应该如何修改架构才能有机会为不同的生物使用许多 typedef?
如果 Mouse 和 Bat 没有默认构造函数,如何更改架构?
非常感谢。
最佳答案
template <class TMouse, class TBat>
class TSuperCreature : public TMouse, public TBat
{
public:
void do() const {
this->walk();
this->fly();
}
};
But I also would like methods Fly and Walk to have parameters (velocity, for example). How should I modify the architecture to have an opportunity to use many typedefs for different creatures? Thanks a lot.
你可以给函数默认参数...
virtual void Walk(double meters_per_second = 1.1) const = 0;
编辑
(from comment below) Imagine that we need 2 creatures: first one walks fast and flies slow, second one is the opposite. That means we have to write 2 typedefs. But I have no idea how to use velovity constants here. Which parts of architecture must have parameters?
一个选择是做这样的事情:
template <class TMouse, class TBat, int walk_speed, int fly_speed>
class TSuperCreature : public TMouse, public TBat
{
public:
void do() const {
this->walk(walk_speed);
this->fly(fly_speed);
}
};
如果你想使用 double
,它们不允许作为模板参数(至少在 C++03 中不允许),但作为 hack 你可以接受一对数字并除以它们在模板中,或者更恰本地说,您可以提供一个策略类....
template <class TMouse, class TBat, class Speeds>
class TSuperCreature : public TMouse, public TBat
{
public:
void do() const {
this->walk(Speeds::walk_speed);
this->fly(Speeds::fly_speed);
}
};
struct Speeds__Fly_Fast__Walk_Slow // yes I know double underscores are reserved - I don't care!
{
static const double walk_speed = 0.5; // m/s
static const double fly_speed = 10;
};
关于c++ - 使用什么架构来暗示一个类中的 2 种行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10951877/