c++ - 如何从其他类 C++ 访问单例

标签 c++ class singleton

虽然我已经搜索了几个小时,但我找不到这个问题的任何 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/

相关文章:

iphone - 在全局范围内使用 MBProgressHUD + 使其成为单例

java - 关于单例类和线程的问题

c++ - 宏是否分配内存?

c++ - 使用 memset 初始化后写入二维数组时出现访问冲突写入错误

python - 在类外部定义的函数的范围是什么?

javascript - document.getElementById 不适用于 <a> 标签

java - 将其他类的图像添加到 JFrame

c++ - 如何通过可变参数模板将多个构造函数参数转发到数组初始值设定项列表?

c++ - 如何为类中可能无法计算的成员设置值?

ios - ARC下sharedInstance模式的内存含义是什么?