2014-02-20 67 views
2

我編碼一個解析器和我有以下接口: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()方法中安裝該測試。

我希望我儘可能清楚地解釋我的問題。你有什麼想法,我該怎麼做乾淨的請嗎?

謝謝:)

回答

2

您的設計似乎有點混亂。

我會作出類,代表{sttmnt1sttmnt2sttmntN}

class Block : public IStatement 
{ 
    std::vector<IStatement*> statements; 
public: 
    virtual void execute(CScope &) const { /* executes list of statements */ } 
}; 

這樣,你永遠如果單個語句的工作,並且可以使用Block類來處理多個語句。

另外一個表達式可以評估的語句的類,如2 < x

class IExpression : public IStatement 
{ 
public: 
    virtual Value evaluate(CScope &scope) const = 0; 
    virtual void execute(CScope &scope) const { evaluate(scope); } 
} 

您將需要一個Value類represente一個表達式的結果。

最後,如果類沃爾德具有作爲屬性爲else第一部分表達,對於if部和另一(可選)一個聲明

class If: public IStatement 
{ 
    IExpression *condition; 
    IStatement *ifPart; 
    IStatement *elsePart; 

public: 
    virtual void execute(CScope &scope) const { 
     if (condition->evaluate().asBoolValue()) { 
      ifPart->execute(scope); 
     } 
     else if (elsePart) { 
      elsePart->execute(scope); 
     } 
    } 
} 

要處理else if箱子你只需要設置一個新的If對象爲第一的else一部分。

+0

感謝您的回答。我會研究你的建議:) – Virus721