저는 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