我編碼一個解析器和我有以下接口:C++接口設計問題
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 ::執行(),無論執行情況的報告,並且,無論manipules類做到這一點本身,而是我想在CConditional :: execute()方法中安裝該測試。
我希望我儘可能清楚地解釋我的問題。你有什麼想法,我該怎麼做乾淨的請嗎?
謝謝:)
感謝您的回答。我會研究你的建議:) – Virus721