虽然我已经搜索了几个小时,但我找不到这个问题的任何 C++ 答案(其他语言是)。我怎样才能从另一个类(class)访问单例?
声明:
#include "Store.h"
Store *store = Store::Instance(); // Singleton
int main()
{
store->GetDepts();
return 0;
}
我希望能够从我的客户代理类访问它:
#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)构造函数:
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++ - 如何从其他类 C++ 访问单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29925106/