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

时间:2011-05-12 06:28:08

标签: c++ inheritance

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

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

接受命令行中的选项。

1 个答案:

答案 0 :(得分:2)

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

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;

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