我正在使用状态机来学习 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
我做错了什么?