在以后的程序中,我有一个类 animal,它派生了 cat 和 dog 具有相同的公共函数但不同的私有函数。我想让用户在运行时决定创建哪种动物。我做了一个简单的例子,展示了我大致想要的东西,但显然不起作用。我不知道如何解决这个问题,希望得到你的帮助。
#include <cstdio>
class canimal
{
public:
int sound()
{
std::printf("...\n");
return 0;
}
};
class cdog : public canimal
{
public:
int sound()
{
std::printf("Woof!\n");
return 0;
}
};
class ccat : public canimal
{
public:
int sound()
{
std::printf("Mieau!\n");
return 0;
}
};
int main()
{
canimal *animal;
cdog *dog;
// I would like to let the user decide here which animal will be made
// In this case, I would like the function to say "Woof!", but of course it doesn't...
animal = new cdog;
animal->sound();
// Here it works, but I would like the pointer to be of the generic class
// such that the type of animal can be chosen at runtime
dog = new cdog;
dog->sound();
return 0;
}