我创建了以下示例来说明现有产品中的设计。我听说应该最小化或删除使用dynamic_cast。我期待社区看看是否有其他/更好的方法来设计它。以下是该计划的简化示例:
#include <vector>
using namespace std;
class Key
{
public:
unsigned int num_teeth;
Key(unsigned int t): num_teeth(t) {}
virtual ~Key() {}
};
class MansionKey:
public Key
{
//mansion keys have chips with frequencies
public:
unsigned int freq;
MansionKey(unsigned int t, unsigned int f):
Key(t), freq(f) {}
virtual ~MansionKey() {}
};
class House
{
public:
void leaveHouse(vector<Key> *vp) {_my_keys = vp;} //take keys with you
void comeBackHome()
{
vector<Key>::iterator iter = _my_keys->begin();
for (; iter != _my_keys->end(); ++iter)
{
if (unlockDoor(&*iter));
break;
}
}
virtual bool unlockDoor (Key * k)
{ return k->num_teeth == door_lock_teeth; }
unsigned int door_lock_teeth;
vector<Key> *_my_keys;
House(){}
virtual ~House() {}
};
class Mansion:
public House
{
public:
unsigned int door_freq;
virtual bool unlockDoor(Key *k)
{
MansionKey *mk = dynamic_cast<MansionKey *>(k); //I know that this is a mansion key
return ((door_lock_teeth == mk->num_teeth) &&
(door_freq == mk->freq));
}
Mansion() {}
virtual ~Mansion() {}
};
int main(int argc, char**argv)
{
House *hp =0;
vector<Key> bagOKeys;
if (argc > 1)
{
//Mansion mode
Mansion *mp = new Mansion();
mp->door_freq = 1024;
mp->door_lock_teeth = 5;
hp= mp;
bagOKeys.push_back(MansionKey(3, 777));
bagOKeys.push_back(MansionKey(5, 1024));
}
else
{
hp = new House();
hp->door_lock_teeth = 7;
bagOKeys.push_back(Key(3));
bagOKeys.push_back(Key(7));
}
hp->leaveHouse(&bagOKeys);
hp->comeBackHome();
delete hp;
}
我想我可以将MansionKey的所有操作复制到Key中,但这往往会打破不是所有键都是豪宅键或具有豪宅键属性的插图。
我希望有一种方法可以为虚拟函数提供专门的模板参数,但语言也不允许这样做。
还有什么其他想法?