带参数的单例模式对象

dav*_*od2 6 c++ singleton design-patterns reference

我正在尝试创建一个C++单例模式对象,使用引用而不是指针,其中构造函数采用2个参数

我已经看过的示例代码的整个主机,其中包括: 在C++单例模式, C++ Singleton设计模式C++单例设计图案

我相信我理解所涉及的原则,但尽管试图几乎直接从示例中提取代码片段,但我无法将其编译.为什么不 - 以及如何使用带参数的构造函数创建此单例模式对象?

我已将收到的错误放在代码注释中.

另外,我在ARMmbed在线编译器中编译这个程序 - 可能/可能没有c ++ 11,我目前正试图找出哪个.

Sensors.h

class Sensors
{
public:
     static Sensors& Instance(PinName lPin, PinName rPin); //Singleton instance creator - needs parameters for constructor I assume
private:
    Sensors(PinName lPin, PinName rPin); //Constructor with 2 object parameters
    Sensors(Sensors const&) = delete; //"Expects ;" - possibly c++11 needed?
    Sensors& operator= (Sensors const&) = delete; //"Expects ;"
};
Run Code Online (Sandbox Code Playgroud)

Sensors.cpp

#include "Sensors.h"
/**
* Constructor for sensor object - takes two object parameters
**/
Sensors::Sensors(PinName lPin, PinName rPin):lhs(lPin), rhs(rPin)
{
}
/**
* Static method to create single instance of Sensors
**/
Sensors& Sensors::Instance(PinName lPin, PinName rPin)
{
    static Sensors& thisInstance(lPin, rPin); //Error: A reference of type "Sensors &" (not const-qualified) cannot be initialized with a value of type "PinName"

    return thisInstance;
}
Run Code Online (Sandbox Code Playgroud)

非常感谢!

Ash*_*hot 7

您应该创建静态局部变量,而不是引用.改为这个.

Sensors& Sensors::Instance(PinName lPin, PinName rPin)
{
    static Sensors thisInstance(lPin, rPin);     
    return thisInstance;
}
Run Code Online (Sandbox Code Playgroud)

这将返回相同的对象(通过首先创建lPinrPin任何时间调用)Sensors::Instance方法.

  • 你应该写`Sensors&Sense = Sensors :: Instance(p19,p20);`现在`Sense`指的是单身对象. (2认同)