0

今後のプログラムでは、公的機能は同じで私的機能が異なる猫と犬のクラスを派生させた動物クラスがあります。実行時にどの動物を作成するかをユーザーに決定させたいと思います。私は私がおおよそ欲しいものを示す簡単な例を作りましたが、それは明らかに機能しません。これを解決する方法がわかりません。ご協力をお願いします。

#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;
}
4

3 に答える 3

3

sound()メソッドを作成する必要がありますvirtual

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

これにより、必要に応じて正確に動作します。

詳細については、C++ で仮想関数が必要な理由を参照してください。

C++ 11 には、override適切に使用すると、特定の種類のエラーの可能性を低くする新しいキーワードがあります。C++ 仮想関数を安全にオーバーライドするを参照してください。

于 2013-03-12T09:21:51.910 に答える
1

あなたは sound() を仮想化しようとしていると思います。C++ のポリモーフィズムについて調べてください。

class canimal
{
  public:
    virtual int sound()
    {
      std::printf("...\n");
      return 0;
    }
};
于 2013-03-12T09:22:10.500 に答える
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;
    }
};
于 2013-03-12T09:23:09.373 に答える