Singleton类 - 真的很困惑

时间:2012-10-27 22:48:26

标签: c++ oop singleton

我试图用C ++实现一个Singleton类并且有点困惑。好吧,假设我有以下两个类:

class Animal {

public:
    virtual int age() = 0;
    virtual void breed() = 0;   
};


class Cat : public Animal {
  public:
Cat();
int age();
void breed();  
};                

这个系统涉及更多的课程....(狗,鱼等)

现在我有一个单例类,我只能使用1个对象:

class Singleton 
{
  public:
    Animal *newAnimal(string theTypeOfAnimal);
  private:   
   static Animal* pinstance;
};                        

Animal *Singleton::newAnimal(string theTypeOfAnimal)
{
pinstance = new Cat;

}           

int main()
{        
Singleton *s;
return 0;
}      

更新:

新代码:

#include <iostream>
using namespace std;

class Animal {

public:
    virtual int age() = 0;
    virtual void breed() = 0;
};

class Cat : public Animal
{
public:
        virtual int age() { return 9; }
        virtual void breed() { }

 };
class Singleton
{
public:
    Animal *newAnimal(string theTypeOfAnimal);
  private:   
   static Animal* pinstance;
};

Animal* Singleton::pinstance = 0;


Animal *Singleton::newAnimal(string theTypeOfAnimal)
{
     this->pinstance = new Cat;
 return pinstance;
}  

 int main(int argc, char *argv[]) {

Singleton s;

Animal *myAnimal = NULL;

Animal *myAnimal = s->newAnimal("cat");

}

3 个答案:

答案 0 :(得分:1)

您需要明确定义静态成员:Animal *Singleton::pinstance = nullptr;

类中的

static Animal* pinstance只是一个声明,即没有为变量分配真实空间。原因是静态成员不属于特定对象,并且未分配托管类的实例。静态成员在所有类实例中共享,必须明确分配。

答案 1 :(得分:1)

您必须在其外部定义静态类对象:

Animal* Singleton::pinstance = 0;

您必须在Cat class:

中定义函数
class Cat : public Animal
{
public:
    Cat() {}
    int age() { return 7; }
    void breed() {}
};

答案 2 :(得分:0)

你必须来自单身人士,而不是来自目标人。 单身人士是一种模式。您可以将其实现为模板类(通常)或基类来派生(罕见)。 经典单身人士有:

  • 私人构造函数
  • privace copy-constructor
  • 私有非虚拟析构函数
  • 私人运营商=
  • 保存指向自我对象的指针
  • 有外部朋友功能来获取对象

它可以:

  • 没有ctor,cctor,dtor和oper =的实现,所以试图从派生类调用它会导致链接错误
  • 私下衍生儿童
  • 懒惰对象初始化
  • ...更多

对于哪种实施更好并且Singleton好坏都没有达成共识。 在我看来,单身对初学者来说比有用更有害。在您确定需要它之前不要使用它。

作为一个沙漠,一个带有智能指针的不良单例模板(发现恐怖错误!):

#include <memory> 
#include <boost/noncopyable.hpp>

template <class T>
class Singleton : public boost::noncopyable
{
public:
    static std::shared_ptr<T> Get()
    {
        if( m_pSelf.get() == 0 )
            return m_pSelf = std::shared_ptr<T>(new T());
        else 
            return m_pSelf;
    }


protected:
    Singleton(){}
    ~Singleton() {}

private:    
    static std::shared_ptr<T> m_pSelf;
};

template <class T> std::shared_ptr<T>  Singleton<T>::m_pSelf;