0

我正在尝试在 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");

}

4

3 回答 3

1

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

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

于 2012-10-28T00:11:05.973 回答
1

您必须在它之外定义静态类对象:

Animal* Singleton::pinstance = 0;

您必须在类中定义函数Cat

class Cat : public Animal
{
public:
    Cat() {}
    int age() { return 7; }
    void breed() {}
};
于 2012-10-28T00:23:40.277 回答
0

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

  • 私有构造函数
  • 隐私复制构造函数
  • 私有非虚拟析构函数
  • 私人运营商=
  • 持有指向自身对象的指针
  • 有外部友元函数来获取对象

它可以:

  • 没有实现 ctor、cctor、dtor 和 oper=,因此尝试从派生类调用它会导致链接错误
  • 私下派生孩子
  • 惰性对象初始化
  • ... 更多的东西

关于哪种实现更好,单例是好还是坏,没有共识。在我看来,单例对初学者来说弊大于利。在确定它在特定地方需要它之前不要使用它。

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

#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;
于 2012-10-27T22:54:18.750 回答