类工厂创建派生类c ++

时间:2015-06-05 07:06:58

标签: c++ oop inheritance factory

我目前正在使用C ++学习类工厂模式。在尝试实施工厂时我一直有错误。假设我有一个抽象类和两个派生类。我希望工厂做的是创建基类的新对象,如下所示:Ball * sc = new SoccerBall(); 我不知道如何实现这一点,我已经尝试但无济于事。我需要修理什么?

class Ball
{
   public:
   Ball();
   virtual ~Ball();
   virtual int getSize() const = 0;
   virtual void setBallSize(int s) = 0;
   virtual string ballManufacturer() const = 0;
   protected:
   int ballSize;
}
class Soccerball:public Ball
{
   public:
   Soccerball();
   Soccerball(int size);
   ~Soccerball();
   int getSize() const;
   void setBallSize(int s);
   string ballManufacturer() const;
}
class Soccerball:public Ball
{
   public:
   Soccerball();
   Soccerball(int size);
   ~Soccerball();
   int getSize() const;
   void setBallSize(int s);
   string ballManufacturer() const;
}
class Basketball:public Ball
{
   public:
   Basketball();
   Basketball(int size);
   ~Basketball();
   int getSize() const;
   void setBallSize(int s);
   string ballManufacturer() const;
}
class BallFactory
{
   public:
   Ball* createBall(string s)
   {
       if(s == "Soccer")
       {
          return new Soccerball(5);
       }
       if(s == "Basket")
       {
          return new Basketball(6);
       }
   }
}

1 个答案:

答案 0 :(得分:0)

这是您的代码如何工作,但在您发布问题时,您应该提供"短自我包含的正确代码"让人们更容易理解你的问题。

#include <iostream>

using namespace std;

class Ball
{
  public:

    Ball()
    {
      cout<<"Ball ctr"<<endl;
    }

    virtual ~Ball()
    {

    }
    virtual int getSize() const = 0;
    virtual void setBallSize(int s) = 0;
    virtual string ballManufacturer() const = 0;

  protected:
    int ballSize;
};

class Soccerball:public Ball
{
  public:

    Soccerball()
    {
     cout<<"create Default Soccer Ball "<<endl;
    }

    Soccerball(int size)
    {
     cout<<"create Soccer Ball "<<size<<endl;
 }

    ~Soccerball()
    {

    }

    int getSize() const
    {
      return ballSize;
    }

    void setBallSize(int s)
    {
      ballSize = s;
    }

    string ballManufacturer() const
    {
      return "";
    }
};

class Basketball:public Ball
{
  public:

    Basketball()
    {
     cout<<"create default Baseket Ball "<<endl;
    }

    Basketball(int size)
    {
     cout<<"create Baseket Ball "<<size<<endl;
    }

 ~Basketball()
    {

    }

    int getSize() const
    {
      return ballSize;
    }

    void setBallSize(int s)
    {
      ballSize = s;
    }

    string ballManufacturer() const
    {
      return "";
    }
};

class BallFactory
{
  public:
//Factory method
    static Ball* createBall(string s)
    {
      if(s == "Soccer")
      {
        return new Soccerball(5);
      }
      if(s == "Basket")
      {
        return new Basketball(6);
      }
    }
};

int main()
{
  Ball* ptr = BallFactory::createBall("Soccer");

  return 0;
}

但您还需要了解Factory设计模式的工作原理以及如何创建同名虚拟构造函数以及使用参数化工厂的原因。或者你可以使用模板工厂吗?