2012-05-26 73 views
0

我正在使用狀態機來學習C++,我想提供一個重載的operator <<來返回相應的字符串,而不是int。道歉的長度...如何從映射的枚舉中正確地重載<<?

#ifndef STATEMACHINE_H 
#define STATEMACHINE_H 

#include <map> 
#include <string> 

namespace statemachine{ 
    using namespace std; 

    enum State { ON, RESTING, SLEEPING, LOCKED, OFF }; 

    struct StateMap : map<unsigned int, string> 
    { 
     StateMap() 
     { 
      this->operator[](ON) = "ON"; 
      this->operator[](RESTING) = "RESTING"; 
      this->operator[](SLEEPING) = "SLEEPING"; 
      this->operator[](LOCKED) = "LOCKED"; 
      this->operator[](OFF) = "OFF"; 
     }; 

     ~StateMap(){}; 
    }; 

struct Machine { 

    Machine(State state) : statemap() { 
     m_currentstate = state; 
    } 

    // trying to overload the operator -- :(
    // Error 1 error C2676: binary '<<' : 'std::ostream' does not define this operator or a 
    // conversion to a type acceptable to the predefined operator **file** 38 1 statemachine_01 
    ostream& operator << (ostream& stream){ 
     stream << statemap[m_currentstate]; 
     return stream; 
    } 

    State state() const { 
     return m_currentstate; 
    } 

    void set_state(State state){ 
     m_currentstate = state; 
    } 

private: 
    State m_currentstate; 
    StateMap statemap; 
}; 

} 

#endif 

我做錯了什麼?

+0

@OliCharlesworth:我看着這個問題,它不完全一樣 - 我們得到兩個不同的編譯錯誤。 – IAbstract

+0

但是這個問題(及其答案)顯示瞭如何正確地重載'operator <<'的代碼片段。 –

+0

@OliCharlesworth:我讀得更遠,發現什麼可行(http://stackoverflow.com/a/9230853/210709)。 – IAbstract

回答

0

您正在定義operator <<Machine的成員。這將意味着,它已被稱爲是這樣的:

machine << stream; 

代替:

stream << machine; 

您需要定義operator作爲一個自由的功能,要能夠接受的參數在右訂購。例如,你可以使它成爲一個friend功能:

friend ostream& operator << (ostream& stream, Machine const& m){ 
    stream << m.statemap[m.m_currentstate]; 
    return stream; 
} 
+0

作者* *您需要將運算符定義爲一個自由函數* ...您的意思是在我的頭文件中,而不是在結構中?對不起,我是C++的新手,並試圖掌握事情的運作方式。我對C#很有經驗。 – IAbstract

+0

@IAbstract:一個自由函數是一個不是類的成員的函數。如果你用我的'operator <<'定義代替它,它應該可以工作。您可能會在頭文件中定義一個自由函數,以避免它們聲明'inline'函數(或將它的定義移動到.cpp文件中),從而開始獲取重複的鏈接器錯誤。 –

+0

我找到了解釋更詳細的解決方案:http://stackoverflow.com/a/9230853/210709 – IAbstract

0

它沒有超載做任何事情(當然,有些也許)。

本聲明

stream << statemap[m_currentstate]; 

失敗,因爲你還沒有定義如何將StateMap適用於< <。

[你必須重載在statemap類< <了。]

對不起,您需要一個獨立的功能,而不是一個方法,看其他的答案。

+0

'statemap [m_currentstate]'返回定義了流輸出的'std :: string'。 –

+0

你是對的。我的回答是無稽之談。 – JohnB