单类实例C ++

时间:2012-04-28 08:31:37

标签: c++ class

是否可以创建一个只能构建一次的类?如果您尝试创建它的其他实例,则应发生编译时错误。

3 个答案:

答案 0 :(得分:5)

实例化在运行时是动态的。编译错误是在编译时。所以答案是否定的,在任何第二次实例化时都不可能得到编译错误。

但是你可以使用单身人士,但要仔细考虑是否真的需要。

答案 1 :(得分:0)

为什么要编译错误?我认为你只需要实现Singleton设计模式。 看here

答案 2 :(得分:0)

只有一个实例的类称为singleton classess,

有很多方法可以执行此操作。最简单的如下所示

class MySingleton
    {
    public:
      static MySingleton& Instance()
      {
        static MySingleton singleton;
        return singleton;
      }

    // Other non-static member functions
    private:
      MySingleton() {};                                 // Private constructor
      MySingleton(const MySingleton&);                 // Prevent copy-construction
      MySingleton& operator=(const MySingleton&);      // Prevent assignment
    };