如何从其他 类 C++ 访问单例
How to access a singleton from other classes C++
虽然我已经搜索了几个小时,但我找不到这个问题的任何 C++ 答案(其他语言是)。如何从另一个 class 访问单例?
声明:
#include "Store.h"
Store *store = Store::Instance(); // Singleton
int main()
{
store->GetDepts();
return 0;
}
我希望能够从我的客户代理访问它 class:
#include "Store.h"
class Cust_Proxy
{
public:
Cust_Proxy(string cust_name)
{
name_ = cust_name;
}
void AddItem(Item item)
{
store->AddItemToShoppingCart(item); // or something, just for example
}
private:
string name_;
ShopCart cart_;
};
我试过将它作为参数传递,但显然单例中没有 public 构造函数 "store":
void AddItem(Store *store)
{
store = Store::Instance();
// Do Stuff;
}
如有任何帮助,我们将不胜感激。谢谢。
而不是
store->AddItemToShoppingCart(item);
使用
Store::instance()->AddItemToShoppingCart(item);
您不需要在 main.cpp
或任何其他使用单例的函数中存储指向单例的指针。需要时通过调用 Store::instance()
来访问单例。
在main
中,您可以使用:
int main()
{
Store::instance()->GetDepts();
return 0;
}
并删除行
Store *store = Store::Instance(); // Singleton
虽然我已经搜索了几个小时,但我找不到这个问题的任何 C++ 答案(其他语言是)。如何从另一个 class 访问单例?
声明:
#include "Store.h"
Store *store = Store::Instance(); // Singleton
int main()
{
store->GetDepts();
return 0;
}
我希望能够从我的客户代理访问它 class:
#include "Store.h"
class Cust_Proxy
{
public:
Cust_Proxy(string cust_name)
{
name_ = cust_name;
}
void AddItem(Item item)
{
store->AddItemToShoppingCart(item); // or something, just for example
}
private:
string name_;
ShopCart cart_;
};
我试过将它作为参数传递,但显然单例中没有 public 构造函数 "store":
void AddItem(Store *store)
{
store = Store::Instance();
// Do Stuff;
}
如有任何帮助,我们将不胜感激。谢谢。
而不是
store->AddItemToShoppingCart(item);
使用
Store::instance()->AddItemToShoppingCart(item);
您不需要在 main.cpp
或任何其他使用单例的函数中存储指向单例的指针。需要时通过调用 Store::instance()
来访问单例。
在main
中,您可以使用:
int main()
{
Store::instance()->GetDepts();
return 0;
}
并删除行
Store *store = Store::Instance(); // Singleton