Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带参数的单例模式对象 我试图创建一个C++单模式对象,使用引用而不是指针,其中构造函数采用2个参数_C++_Design Patterns_Reference_Singleton - Fatal编程技术网

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

带参数的单例模式对象 我试图创建一个C++单模式对象,使用引用而不是指针,其中构造函数采用2个参数,c++,design-patterns,reference,singleton,C++,Design Patterns,Reference,Singleton,我查看了大量示例代码,包括: , 及 我相信我理解所涉及的原则,但尽管我试图几乎直接从示例中提取代码片段,但我无法将其编译。为什么不呢?我如何使用带参数的构造函数创建这个单例模式对象 我已将收到的错误放在代码注释中 另外,我在ARMMALL在线编译器中编译这个程序,它可能不包含C++ 11,我现在正在试图找出哪个。 传感器 传感器.cpp 非常感谢 您应该创建静态局部变量,而不是引用。换成这个 Sensors& Sensors::Instance(PinName lPin, PinNa

我查看了大量示例代码,包括: , 及

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

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

另外,我在ARMMALL在线编译器中编译这个程序,它可能不包含C++ 11,我现在正在试图找出哪个。 传感器 传感器.cpp
非常感谢

您应该创建静态局部变量,而不是引用。换成这个

Sensors& Sensors::Instance(PinName lPin, PinName rPin)
{
    static Sensors thisInstance(lPin, rPin);     
    return thisInstance;
}

这将在任何时候调用
Sensors::Instance
方法时返回相同的对象(由first
lPin
rPin
创建)

这看起来比通常的单例方法更加错误。想象一下这段代码:
Sensors::Instance(foo,bar).doSomething();传感器::实例(baz,qux).doSomething()。第二次调用将公然忽略参数,这在调用站点上根本不明显。这是否重要?由于它不应该创建新对象,而是返回原始对象,因此忽略参数是否重要?如果应该检查参数,那么在返回原始对象之前在方法中添加一个验证步骤不是很简单吗?问题是它们在代码中不会很好地相互遵循。假设您只看到
Sensors::Instance(alpha,beta).doSomething()SOM在代码中的位置。您无法知道该实例是否实际具有参数
alpha
beta
,或者它是否将在上一次调用中使用可能完全不同的参数创建的实例上执行操作。谢谢。我现在尝试创建这样的opject:Sensors Sense=Sensors.Instance(第19页,第20页);然而,很明显,“main.cpp”中不允许使用“Type name”-我如何实例化我的单例对象?再次感谢!您应该编写
Sensors&Sense=Sensors::Instance(p19,p20);
现在
Sense
指的是单例对象。
#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;
}