【发布时间】:2014-03-21 18:02:21
【问题描述】:
我正在编写一个解析器,我有以下界面:
class IStatement
{
// Represents instructions like "HelloWorld();"
// Or flow control blocks like : "if( foo ) { bar(); }", "return 0;" etc...
public:
virtual void execute( CScope & ) const = 0;
};
还有以下类:
class CGoto : public IStatement // Basically a sequence of IStatement sub classes.
{
protected:
vector<IStatement *>
public:
virtual void execute( CScope & ) const; // Executes all statements.
};
class CConditional : public CGoto
{
protected:
CExpression // Condition that must be true
public:
virtual void execute( CScope & ) const; // If expression is true, executes all statements (i.e call CGoto::execute()).
};
我的问题是我想创建一个 CIf 类:
class CIf : public CConditional // Repesents a whole if/else if/ else block.
{
// "this" is the "if" part of the if/else if/else block
vector<CConditional *> _apoElseIfs; // "else if" parts, if any.
CConditional * _poElse; // NULL if no "else" in if/else if/else block.
public:
virtual void execute( CScope & roScope ) const
{
// HERE is my problem !
// If the condition in the "if" part is true, i'm not going to execute
// the else if's or the else.
// The problem is that i have no idea from here if i should return because the
// if was executed, or if i should continue to the else if's and the else.
CConditional::execute( roScope );
// Was the condition of the "if" true ? (i.e return at this point)
// For each else if
{
current else if -> execute( roScope );
// Was the condition of the current "else if" true ? (i.e return at this point)
}
else -> execute( roScope );
}
};
我不知道,在我执行了“if”或“else if”之后,我应该继续还是返回。
我认为我可以使用布尔值作为 execute() 方法的返回值,以指示语句是否已执行,但这对于非条件 IStatement 的实现没有意义。
我也可以使 CConditional 类不测试条件本身,并且 CConditional::execute() 执行语句而不管条件如何,并且无论对类的任何操作都可以自己执行,但是我想将该测试封装在 CConditional::execute() 方法中。
我希望我尽可能清楚地解释了我的问题。你知道我怎么能干净地做到这一点吗?
谢谢你:)
【问题讨论】:
标签: c++ inheritance interface polymorphism