C++ 所有者类和子类的派生类

标签 c++ oop design-patterns inheritance

假设我有一个由动物园类管理的动物类。

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/

相关文章:

Java - 如何为类外变量抛出 IllegalArgumentException

c++ - 单例模式与工厂模式的争议

user-interface - 什么是 MVP 和 MVC,有什么区别?

api - API(如 Web API)基于什么设计模式(如果有)?

c++ - 从另一个线程关闭 QTcpSocket

c++ - 如何缩短巨大 bool 表达式的编译时间?

javascript - prototype.constructor 和内置 Object() 有什么区别

java - 优先组合而不是继承

c++ - 一次发布多个数据

c++ - 为 boost 的变换迭代器寻找复合特征模式