我有一个派生自多个基类的类,我想使其成为一个单例。问题是派生类和基类不使用默认构造函数并接受参数,因此我对如何进行管理感到困惑。我希望能够将参数传递给构造函数,但是我只想做一次(我不希望它成为setter)。我唯一的解决方案是派生类的getInstance()成员中的静态布尔值。
基本情况:
//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);
我正在寻找有关如何执行此操作的方向,或者也许是我根本不应该执行此操作的原因?谢谢
最佳答案
干得好。而不是参考,我在这里使用指针。这只是一个示例,因此我不能使此单例成为线程安全的。还要将默认构造函数声明为私有,这样就无法实例化。
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;
}
关于c++ - 具有非默认构造函数的多个基的Singleton派生类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47023341/