【问题标题】:using singleton class to be reached from all classes使用单例类从所有类中访问
【发布时间】:2016-09-16 19:31:32
【问题描述】:

我有一个奇怪的问题。这太奇怪了,可能很容易解决。

我创建了一个软件,我需要实现一个 Sing 类,其中包含一个必须从该软件的所有类中访问的 sing 对象。因此我在主函数中将它创建为单例对象。

我的问题是,如何在不创建指针的情况下从其他类(如 ClassA)访问对象 sing,这些指针由指向代码中每个类的指针传递。

所有的类定义都位于 sing.h 文件中。如果我将定义放入 sing.cpp 文件中,编译器将失败。

我设法创建了这个 sing 对象,但它在 ClassA 中不可见。不把指针交给各个类的构造函数,怎么能看到对象唱歌呢?

sing.h 文件:

#ifndef _SING_H_
#define _SING_H_

//declaration
class Singleton
{
public:
    static Singleton* Instance();
    static Singleton* InstanceSlave();
    int a;
    int setTest(int);

protected:
    Singleton(){}

private:
    static Singleton* _instance;    
    static Singleton* _instanceSlave;

};

//definitions (only work in header file, not in .cpp file

Singleton* Singleton::_instance =0;

Singleton* Singleton::Instance()
{

    if (_instance == 0 )
    {
        _instance = new Singleton;
    }
    return _instance;

}

int Singleton::setTest(int b)
{
 return 1;
}

#endif _CONF_H_

main.cpp 文件:

int main()
{
 Singleton* sing = sing->Instance();
 sing->setTest(2);

 ClassA* classa = new ClassA();
}

main.h 文件:

#inlucde <iostream>
#include "sing.h"
#include "classA.h"

在 ClassA 里面我想要这样的东西:

classA.h

#inlude sing.h
class classA
{
 public:
  void doSomeThing(int);
}

classA.cpp:

#include ClassA.h
{
 void ClassA::doSomeThing(int a)
 {
  sing.setTest(a);
 }
}

【问题讨论】:

  • 每个以下划线后跟大写字母的名称都保留给实现。你不应该定义_SING_H_。例如,SING_H_ 可以。

标签: c++ object namespaces singleton global


【解决方案1】:

我的问题是,如何在不创建指针的情况下从其他类(如 ClassA)访问对象 sing,这些指针由指向代码中每个类的指针传递。

规范的方法是使用Scott Meyer's Singleton 并提供类似的静态函数

    static Singleton& Instance() {
         static Singleton theInstance;
         return theInstance;
    }

用法是

Singleton::Instance().setTest(2);

一般来说,单例模式并不是真正的好技术,因为与其余代码的耦合太紧密了。最好使用接口(抽象类)并根据需要传递它们。

【讨论】:

    【解决方案2】:

    随便用

    Singleton::Instance()->setTest(a);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多