如何使用动态绑定继承适当的类

How to inherit appropriate class using dynamic binding?

本文关键字:继承 何使用 动态绑定      更新时间:2023-10-16

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

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

从命令行接受选项。

你必须显式构造正确的类(伪代码):

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;

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