假设我有一个由动物园类管理的动物类。
Animal is an abstract class to be derived by other real animal classes
class Animal{
public:
Animal();
virtual ~Animal() = 0;
//Various animal related functions
}
class Zoo{
public:
Zoo();
virtual ~Zoo();
virtual void updateAll();
//And various other functions dealing with animals
private:
vector<animal*> animals
}
现在假设我想创建一个bird_zoo,并且我想重用大部分代码 用于 Zoo 类和 Animal 类。
所以我开设了鸟类类(class)
class Bird : public Animal{
public:
Bird();
virtual ~Bird();
//all the various functions derived from Animal class
virtual void fly(); //New function that Animal didn't have
}
class Bird_Zoo : public Zoo{
public:
Bird_Zoo();
virtual ~Bird_Zoo();
//And various other functions dealing with animals, derived from Zoo
virtual void flyAll(); //New function that Zoo didn't have
private:
//vector<??????> birds
}
我如何拥有这个Bird_Zoo
它有处理鸟类的功能吗?
如果我和vector<Animal*>
在一起动物园课上,我怎么打电话fly()
?
我真的必须将其转换到 Bird*
每次?
有没有办法从概念上“重载”vector<Animal*>
如vector<Bird*>
,
这样所有旧的 Zoo 功能仍然可以正常工作吗?
谢谢。
最佳答案
另一种可能性是使用模板。
class Zoo {
// ...
virtual void updateAll() = 0;
};
template <typename T,
typename = typename enable_if<is_base_of<Animal, T>::value>::type>
class ZooWithAVector : public AbstractZoo {
public:
virtual void updateAll() { /* ... */ }
// Various functions dealing with T-animals
private:
vector<T*> animals;
};
typedef ZooWithAVector<Animal> TypicalZoo;
class BirdZoo : public ZooWithAVector<Bird> {
virtual void flyAll() { /* work with the vector<Bird> */ }
};
关于C++ 所有者类和子类的派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9726753/