代码之家  ›  专栏  ›  技术社区  ›  buttercup

C++/CLI中的单例实例?

  •  11
  • buttercup  · 技术社区  · 15 年前

    我已经浏览过了,我需要一个例子,它在2个或多个C++/CLI文件中工作。

    如何在C++/CLI中声明一个单元格,而不是C++?

    如何在两个或多个C++/CLI文件中共享该单子?

    当我尝试分享这个单例时,我总是得到变量的重新定义。

    2 回复  |  直到 15 年前
        1
  •  17
  •   Ben Voigt    15 年前

    这是C++/CLI,不是“.NET托管扩展的C++”,又名C++.NET。不要使用托管扩展(Visual Studio 2002-2003),它们有问题。

    ref class Singleton
    {
    private:
      Singleton() {}
      Singleton(const Singleton%) { throw gcnew System::InvalidOperationException("singleton cannot be copy-constructed"); }
      static Singleton m_instance;
    
     public:
      static property Singleton^ Instance { Singleton^ get() { return %m_instance; } }
    };
    

    对于“跨多个文件”,同一项目中的其他编译单元使用 #include ,其他程序集使用引用(或 #import )这样就不会有任何重新定义的问题。

    推荐文章