我正在使用狀態機來學習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
我做錯了什麼?
@OliCharlesworth:我看着這個問題,它不完全一樣 - 我們得到兩個不同的編譯錯誤。 – IAbstract
但是這個問題(及其答案)顯示瞭如何正確地重載'operator <<'的代碼片段。 –
@OliCharlesworth:我讀得更遠,發現什麼可行(http://stackoverflow.com/a/9230853/210709)。 – IAbstract