我有一个派生自多个基类的类,我想让它成为一个单例。问题是派生的,基类不使用默认构造函数并接受参数,所以我很困惑如何管理。我希望能够将参数传递给构造函数,但我只想做一次(我不希望它成为一个setter)。我唯一的解决方案是派生类的getInstance()成员中的静态bool值。
基本情况:
//Singleton Derived Class with multiple bases of non-default constructors
class base1 {
public:
base1(int* value) :
val_{value} {;}
~base1();
private:
int val_;
}
class base2 {
public:
base2(int* value) :
val_{value} {;}
~base2();
private:
int val_;
}
class derived : public base1, public base2 {
public:
derived(int* value) :
base1{value}, //Base 1 constructor call
base2{value}, //Base 2 constructor call
val_{value} {;}
~derived();
private:
int val_;
}
//Creation
derived newDerived(&value);
试图让它像单身一样吗?
//Lets make it a singleton
class base1 {
public:
base1(); //Can I pass the construtor anything?
~base1();
private:
int val_;
}
class base2 {
public:
base2(); //Can I pass the construtor anything?
~base2();
private:
int val_;
}
class derived : public base1, public base2 {
public:
static derived& getInstance(int* value) {
static bool init;
if (!init) {
base1::val_ = value;
base2::val_ = value;
init=true;
}
static derived instance;
return instance;
}
derived(int* value) {;}
~derived();
private:
derived(derived const&) = delete; //Copy construct
derived(derived&&) = delete; //Move construct
derived& operator=(derived const&) = delete;//Copy assign
derived& operator=(derived &&) = delete; //Move assign
int val_;
}
//Creation
derived::getInstance(&value);
我正在寻找一些关于我应该怎么做的方向,或者我可能不应该这样做的原因?感谢
答案 0 :(得分:1)
你走了。而不是引用我在这里使用指针。这只是一个例子,因此我没有将这个单例作为线程安全。还将默认构造函数声明为private,以便它不能实例化。
class base1 {
public:
base1(int* value) : val_(*value) {}
~base1() {};
private:
int val_;
};
class base2 {
public:
base2(int* value) :
val_(*value ) { }
~base2() {};
private:
int val_;
};
class derived : public base1, public base2 {
private:
derived(int* value) :
base1(value), //Base 1 constructor call
base2(value), //Base 2 constructor call
val_(*value) {}
~derived() {};
private:
int val_;
static derived* driv;
public:
static derived* getInstance(int* value);
};
derived* derived::driv = NULL;
derived* derived::getInstance(int* value)
{
if (driv == NULL)
{
driv = new derived(value);
}
return driv;
}