C++多态性-找出派生类的类型
C++ Polymorphism- find out type of derived class
我有如下的类层次结构:
class ANIMAL
{
public:
ANIMAL(...)
: ...
{
}
virtual ~ANIMAL()
{}
bool Reproduce(CELL field[40][30], int x, int y);
};
class HERBIVORE : public ANIMAL
{
public:
HERBIVORE(...)
: ANIMAL(...)
{}
};
class RABBIT : public HERBIVORE
{
public:
RABBIT()
: HERBIVORE(10, 45, 3, 25, 10, .50, 40)
{}
};
class CARNIVORE : public ANIMAL
{
public:
CARNIVORE(...)
: ANIMAL(...)
{}
};
class WOLF : public CARNIVORE
{
public:
WOLF()
: CARNIVORE(150, 200, 2, 50, 45, .40, 190, 40, 120)
{}
};
我的问题:
所有的动物都必须繁殖,而且它们都以同样的方式繁殖。在这个例子中,我只包括rabbits
和wolves
,但是我包括更多的Animals
。
我的问题:
如何修改ANIMAL::Reproduce()
以找出位置field[x][y]
上的动物类型,并在该特定类型上调用new()
?(即rabbit
将呼叫new rabbit()
,wolf
将呼叫new wolf()
)
bool ANIMAL::Reproduce(CELL field[40][30], int x, int y)
{
//field[x][y] holds the animal that must reproduce
//find out what type of animal I am
//reproduce, spawn underneath me
field[x+1][y] = new /*rabbit/wolf/any animal I decide to make*/;
}
在Animal:中定义一个纯虚拟方法clone
virtual Animal* clone () const = 0;
然后,像兔子这样的特定动物会将克隆定义如下:
Rabbit* clone () const {
return new Rabbit(*this);}
返回类型是协变的,所以Rabbit*
在Rabbit的定义中是可以的。它不一定是动物。
对所有动物都这样做。
然后在重放中,只需调用clone()
。
相关文章:
- 存储模板类型以强制转换回派生<T>
- 在 C++ 中用派生类型重写成员函数
- 检查一个类型是否直接派生自"enable if"上下文中的另一个类型(是其子类型)
- 给定一个类型,如何派生一个泛型更广泛的类型(例如,用于溢出安全求和)?
- 在 C++ 中将对象转换为派生类型
- 如何检查派生类的类型?(C++实例)
- 创建派生自可变参数模板包的类型元组
- C++如果采用类类型的函数被传递派生类型,有没有办法给出错误?
- 返回派生类型时出现协变类型错误
- 静态自动 constexpr t = { "red" , "black" , "green" } 是什么类型;派生到?
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- 在从仅移动类型派生的类中定义析构函数在使用 std::vector emplace_back或push_back创建时会
- (C++);动态决定函数的类型(派生类)
- 如何使variadic模板类方法以函数指针为参数,类型派生自函数模板
- 如何防止从 c++03 中的类型派生
- 如何为从特定类型派生的类型专门化模板
- 为什么在返回从函数的返回类型派生的类型本地对象时不选择 move 构造函数?
- 如何在模板类型中强制静态成员初始化?或如何获取从模板类型派生的所有类的计数
- 有没有任何方法可以从C++中的成员指针类型派生对象类型
- 在c++中基于另一个变量类型派生一个变量类型