2011-12-23 115 views
1

我現在有一個錯誤,我有點困惑。我在班上有一個getter/setter。 setter接受一個枚舉作爲參數,getter應該返回這個枚舉。不過,我得到這個錯誤,吸氣:爲什麼可以將枚舉作爲函數變量傳遞,但不返回枚舉?

error: C2143: syntax error : missing ';' before 'Session::type'

彷彿SessionType是不確定的。但是我沒有得到同樣的錯誤。有什麼理由?有沒有辦法解決這個錯誤?

(順便說一下,它編譯罰款,如果我返回int但我寧願保持的getter與setter方法一致)

這裏是我的代碼:

Session.h

class Session { 

public: 

    enum SessionType { 
     FreeStyle, 
     TypeIn, 
     MCQ 
    }; 

    explicit Session(); 
    SessionType type() const; 
    void setType(SessionType v); 

private: 

    SessionType type_; 

} 

Session.cpp:

SessionType Session::type() const { // ERROR!! 
    return type_; 
} 

void Session::setType(SessionType v) { // No error? 
    if (type_ == v) return; 
    type_ = v; 
} 

回答

4

問題是,當您在評估返回類型時,在Session.cpp中定義函數時,編譯器尚未意識到它是該類的成員函數,並且不會有這樣的枚舉範圍。它與該函數的從左到右的定義有關。試試這個

Session::SessionType Session::type() const { // ERROR!! 
    return type_; 
} 

注意,其他的情況下工作,因爲直到它的評價函數的名稱,因此具有範圍枚舉它不會遇到枚舉。

此外,您得到的錯誤是由於類定義末尾缺少分號。

7

變化

SessionType Session::type() const { // ERROR!! 

Session::SessionType Session::type() const { 
+1

澄清這一點:SessionType是Session的成員,因此您需要使用完全限定類型名稱,即Session :: SessionType。如果直接在類體內定義type(),則不必指定Session ::。 – onitake 2011-12-23 14:03:36

+0

@Laurent:無論如何! – NPE 2011-12-23 14:16:48

3

你忘了關類聲明:

class Session { 

public: 

    enum SessionType { 
     FreeStyle, 
     TypeIn, 
     MCQ 
    }; 

    explicit Session(); 
    SessionType type() const; 
    void setType(SessionType v); 

private: 

    SessionType type_; 

}; // <- semicolon here 

,你需要限定類的外部enum名稱:

Session::SessionType