如何在单例中传递参数 [英] How to pass argument in a singleton
问题描述
我一直想知道如何将参数传递给单例构造函数。我已经知道如何做单身人士了,但是我很不幸找到了一种方法。
I've been wondering how to pass argument to a singleton contructor. I already know how to do a singleton, but I've been unlucky to find a way to do it.
这是我的代码(其中一部分)。
Here is my code (part of it).
Questionnary* Questionnary::getInstance(){
static Questionnary *questionnary = NULL;
if(questionnary == NULL){
cout << "Object created";
questionnary = new Questionnary();
}
else if(questionnary != NULL){
cout << "Object exist";
}
return questionnary;
}
Questionnary::Questionnary(){
cout << "I am an object";
}
//This is want i want to acheive
Questionnary::Questionnary(string name){
cout << "My name is << name;
}
在此先谢谢了
(顺便说一句,我知道如何并且为什么单身人士不好)
(BTW i know how and why a singleton is bad)
推荐答案
您不需要动态分配单例实例,它可以采用以下方式(有时称为延迟加载单例〜实例创建得很晚,并且有点自动):
You don't need to allocate the instance of singleton dynamically. It could look the following way (this is sometimes called "lazy loading singleton" ~ the instance is created late & kinda "automatically"):
#include <iostream>
#include <string>
class Questionnary
{
private:
// constructor taking string:
Questionnary(const std::string& name) : name_(name) { }
public:
static Questionnary& getInstance(const std::string& name)
{
static Questionnary q(name);
std::cout << "My name is: " << q.name_ << std::endl;
return q;
}
private:
std::string name_;
};
int main() {
Questionnary::getInstance("Josh");
Questionnary::getInstance("Harry");
}
输出:
My name is: Josh
My name is: Josh
请注意,第一次调用 getInstance
时,构造函数将仅被调用一次。
Note that constructor will be called only once right when the getInstance
is called for the first time.
这篇关于如何在单例中传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!