C ++多态加载/保存 [英] C++ polymorphic load/save

查看:128
本文介绍了C ++多态加载/保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我保存并重新加载一堆不同的对象,所有对象都从一个公共基础派生到一个文件,显然我需要存储类名(或类似的东西),以便在重新加载时创建正确的对象类型。 / p>

节省是很容易的:

  class Base 
{
virtual string className()const = 0;

void saveToFile()
{
write(className());
...其他编写的东西
}
}

类Derived1:public Base
{
string className()const {return Derived1; };
...
}

class Derived2:public Base
{
string className()const {returnDerived2; };
...
}

重复字符串...

  static Base * Base :: factory(const String& cname)
{
if(cname ==Derived1)
return new Derived1;
else if(cname ==Derived2)
return = new Derived2;
else ...
}

void load()
{
String cname = readString();

Base * obj(Base :: factory(cname);

obj-> readIt();
}

但是,重复的字符串违反了我的DRY感觉:理想情况下, className() static virtual 但是这是不允许的。我有一种感觉,我缺少一个明显的干净的方式,但我还看不到它。任何建议?



注意:好的,使用工厂方法稍微调整代码注意,这不会真正回答问题!



注意#2:上面的代码并不是一个完美的代表性的最终工厂模式。我不关心基础和派生类之间不必要的链接,或扩展层次结构的潜在困难。我正在寻找可以简化代码而不是使其复杂化的答案。

解决方案

这是关于你能做的最好的可以通过在工厂类中包装 if 来清理它。


I'm saving and reloading a bunch of different objects all derived from a common base to a file, and obviously I need to store the class name (or something similar) in order to create the correct object type on reloading.

Saving is easy:

class Base 
{
  virtual string className() const = 0;

  void saveToFile()
  {
    write(className());
    ... other writing stuff
  }
}

class Derived1: public Base 
{
  string className() const { return "Derived1"; };
  ...
}

class Derived2: public Base 
{
  string className() const { return "Derived2"; };
  ...
}

and, loading is easy if you don't mind duplicating the strings...

static Base * Base::factory(const String &cname)
{
  if (cname == "Derived1")
    return new Derived1; 
  else if (cname == "Derived2")
    return = new Derived2; 
  else ...
}

void load()
{
  String cname = readString();

  Base * obj(Base::factory(cname);

  obj->readIt();
}

But, the duplicated strings offends my sense of DRY: Ideally, className() could be static virtual but that isn't allowed. I have a feeling that I'm missing an obvious 'clean' way round this, but I can't see it yet. Any suggestions?

Note: OK, code slightly tweaked using a factory method. Note that this doesn't actually answer the problem!

Note #2: The code above isn't trying to be a perfect representation of the ultimate factory pattern. I'm not concerned with unwanted linkage between base and derived classes, or potential difficulties in extending the hierarchy. I'm looking for answers that will simplify the code rather than complicate it.

解决方案

That's about the best you could do, you might clean it up a bit though by wrapping the if in a factory class.

这篇关于C ++多态加载/保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆