【问题标题】:How to inherit appropriate class using dynamic binding?如何使用动态绑定继承适当的类?
【发布时间】:2011-05-12 06:28:08
【问题描述】:

我有一个程序,它具有抽象基 class FILEPARSER,它有两个虚拟方法 read() 和 print()。 从这个基类继承的两个类是:XMLPARSER 和 CONFIGPARSER,它们将实现方法。

主程序应该接受文件“config”或“xml”的类型并继承该类型的适当类?

从命令行接受选项。

【问题讨论】:

  • 你的意思是实例化正确的派生类吗?
  • 有什么问题?发布一些代码来展示你做了什么。

标签: c++ inheritance


【解决方案1】:

你必须明确地构造正确的类(伪代码):

FileParser* parser = 0;
ParserType type = //retrieve the type you need
switch( type ) {
case ParserTypeConfig:
    parser = new ConfigParser();
    break;
case ParserTypeXml:
    parser = new XmlParser();
    break;
default:
    //handle error
};

//then at some point you use the created object by calling virtual functions
parser->read(blahblahblah);
parser->print();

// and then at some point you delete the heap-allocated object
delete parser;
parser = 0;

当然你应该使用智能指针来处理堆分配的对象。

【讨论】:

  • 一个令人困惑的问题的好答案。
猜你喜欢
  • 2018-03-10
  • 2012-09-25
  • 2016-03-12
  • 2011-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多