如何在没有单例的情况下创建此类的单个实例,以及如何声明它以便另一个类可以在不全局声明的情况下访问它?
请阅读代码(尤其是注释)以获得更好的理解:
#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;
};