C++ Are there any good alternatives to global declaration of this class and singleton?
本问题已经有最佳答案,请猛点这里访问。
如何在没有singleton的情况下生成此类的单个实例,以及如何声明它,以便另一个类可以在不全局声明的情况下访问它?
请阅读代码(尤其是注释),以便更好地理解:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | #include <iostream> #include <vector> // The only class that will be using this class is Obj... // There can only be a single instance of ObjManager but how can I do that // without singleton??? class ObjManager { friend class Obj; int i; }; // Since I cannot think of a better way of accessing the SAME and ONLY ObjManager, I // have decided to declare a global instance of ObjManager so every instance of // Obj can access it. ObjManager g_ObjManager; class Obj { friend class ObjManager; public: void Set(int i); int Get(); }; void Obj::Set(int i) { g_ObjManager.i += i; }; int Obj::Get() { return g_ObjManager.i; }; int main() { Obj first_obj, second_obj; first_obj.Set(5); std::cout << second_obj.Get() << std::endl; // Should be 5. second_obj.Set(10); std::cout << first_obj.Get() << std::endl; // Should be 15. std::cin.get(); return 0; }; |
为什么不这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class ObjManager { private: ObjManager() {} public: static ObjManager& get() { static ObjectManager m; return m; } friend class Obj; int i; }; |
然后打电话给
如果希望所有
1 2 3 4 5 6 7 | class ObjManager { ... }; class Obj { private: static ObjManager manager; }; |
然后,当您创建一个