[英]How to access a singleton from other classes C++
盡管已經搜索了多個小時,但我找不到C ++這個問題的任何答案(對於其他語言是)。 如何從另一個班級訪問Singleton?
宣言:
#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_;
};
我嘗試將其作為參數傳遞,但顯然在單例“存儲”中沒有公共構造函數:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.