因此,在您让我失望之前,告诉我这是一件可怕的事情,我只想声明,出于好奇和可能的代码减少,我想知道这一点。我想要一个实现派生类单例的基类。但是,这样做会从派生类中丢失数据。如何获得派生类方面的基类以实现单例。例如:
class Application{
public:
/**
* @brief instance: C++11 [If control enters the declaration concurrently while the variable is being initialized,
*the concurrent execution shall wait for completion of the initialization.—§6.7 [stmt.dcl] p4]
* @return handle to application
*/
static Application& instance(){
static Application s_Application;
return s_Application;
}
void setName(std::string Name){
AppName=Name;
}
std::string getName(){
return AppName;
}
virtual ~Application(){ }
private:
Application(){}
std::string AppName;
};
现在,我创建一个继承自Application的派生类:
class Test:public Application{
public:
void printer(std::string test){
std::cout<<"test\n";
}
};
int main(int argc, char *argv[]) {
Application test1=Test::instance();
//Test test2=static_cast<Test>(test1);
test1.setName("bla");
test1.printer(test1.getName());
}
因此,正如预期的那样,由于返回的对象为“应用程序”类型,因此test1无法调用.printer()方法。有什么方法可以将派生类的类型传递回主类并创建派生类的实例?
编辑:我已经使用CRTP来传递值,但是当我执行以下操作时,它彼此不相等:
Test test1=Test::instance();
Test test2=Test::instance();
cout<<"Is test1 the same as test 2? "<<(&test1==&test2)<<endl;
结果总是FALSE。
您还需要将复制构造函数和赋值设置为私有,以便不能复制对象(因为仅必须存在对象)。
在你的代码中
Test test1=Test::instance();
Test test2=Test::instance();
你实际上是在打电话
Test test1(Test::instance());
实际上是在呼唤
Test (const Test &);
这是副本构造函数,因此可以创建对象的副本。您实际上正在创建两个不同的对象。这就是为什么他们的地址不同的原因。
因此,将复制构造函数和赋值运算符设为私有,以便没人能复制它。
并使用以下
Test & test1 = Test::instance();
Test & test2 = Test::instance();
在这种情况下,地址将相同。
或者,您可以根据需要返回指针Test::instance
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句