我正在尝试使用引用而不是指针创建C ++单例模式对象,其中构造函数采用2个参数
我已经看过整个主机的示例代码,其中包括:在C ++单例模式,C ++ Singleton设计模式和C ++单例设计图案
我相信我了解所涉及的原理,但是尽管尝试从示例中直接摘录代码片段,但仍无法编译。为什么不-如何使用带有参数的构造函数创建此单例模式对象?
我已将收到的错误放入代码注释中。
另外,我正在ARMmbed在线编译器中编译该程序-可能/可能没有c ++ 11,我目前正试图找出哪个。
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 ;"
};
#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;
}
非常感谢!
您应该创建静态局部变量,而不是引用。改成这个。
Sensors& Sensors::Instance(PinName lPin, PinName rPin)
{
static Sensors thisInstance(lPin, rPin);
return thisInstance;
}
任何时候调用方法都会返回相同的对象(由firstlPin
和创建rPin
)Sensors::Instance
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句