我有一个抽象类,让它成为例如Animal。动物有一个纯粹的虚拟功能吃,如果他们不想饿死,每只动物必须实施。我保证只动物的孩子可以用这种方式进行实例化:C++使用纯虚函数实例化抽象类的子代
Animal.hpp
class Animal
{
public:
enum eAnimal{
CAT=0,
DOG=1,
BIRD=2
};
// Instantiates the desired animal.
static Animal GetAnimal(const int animal);
virtual void Eat() const = 0;
protected:
Animal();
};
Animal.cpp
Animal Animal::GetAnimal(const int animal)
{
switch(animal)
{
case CAT:
return Cat();
case DOG:
return Dog();
case BIRD:
return Bird();
default:
cerr << "Animal not recognized." << endl;
exit(-1);
}
}
Animal::Animal()
{}
有了这个,一个猫将是:
Cat.hpp
class Cat : public Animal
{
public:
Cat();
void Eat() const;
};
Cat.cpp
Cat::Cat() : Animal()
{}
void Cat::Eat() const
{
// The cat eats.
}
但是这个代码不工作,它得到一个错误无效抽象的返回类型“动物”在GetAnimal,因为动物是抽象的,不能被实例化,尽管我的API确保它不会。
这个问题有哪些智能解决方案?我可以做的功能吃不纯,并给它一个默认的实现,但我不想这样做。
@Galik有些相机是动物。 –
虚拟成员函数使用指针 – Amadeus
您确定首先需要运行时多态吗? – SergeyA