将派生类转换为具有相同公共函数的泛型类类型,同时仍然能够调用派生类的函数

时间:2013-03-12 09:19:07

标签: c++ class inheritance casting

在以后的程序中,我有一个类动物,它具有派生类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;
}

3 个答案:

答案 0 :(得分:3)

您需要制作sound()方法virtual

class canimal
{
  public:
    virtual int sound()
    ^^^^^^^

这将使其完全符合您的需要。

有关进一步的讨论,请参阅Why do we need Virtual Functions in C++?

在C ++ 11中,有一个新的override关键字,如果使用得当,会降低某些类型的错误。见Safely override C++ virtual functions

答案 1 :(得分:1)

我认为你正在寻找声音()虚拟。阅读C ++中的多态性。

class canimal
{
  public:
    virtual int sound()
    {
      std::printf("...\n");
      return 0;
    }
};

答案 2 :(得分:1)

您需要使用virtual

class canimal
{
  public:
    virtual int sound()
    {
      std::printf("...\n");
      return 0;
    }
};

class cdog : public canimal
{
  public:
    virtual int sound()
    {
      std::printf("Woof!\n");
      return 0;
    }
};

class ccat : public canimal
{
  public:
    virtual int sound()
    {
      std::printf("Mieau!\n");
      return 0;
    }
};