开发者

How to inherit appropriate class using dynamic binding?

I have a program which has abstract base class FILEPARSER that has two virtual methods read() and print(). Two classes inherited from this base class are: XMLPARSER and CONFIGPARSER that will implement methods.

the main program should accept the type of file "config" or "xml" and inherit the appropriate class for that type?

accepting the options from commandline开发者_运维百科.


You'll have to explicitly construct the right class (pseudocode):

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;

of course you should use a smart pointer to handle the heap-allocated object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜