如何重载<<从映射的枚举中正确吗?

时间:2012-05-26 17:55:33

标签: visual-c++

我正在使用状态机来学习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

我做错了什么?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

它不需要对重载做任何事情(好吧,有些可能)。

本声明

stream << statemap[m_currentstate];

失败,因为您尚未定义如何将StateMap应用于&lt;&lt;。

[你必须重载&lt;&lt;在statemap类中也是如此。]

抱歉,您需要一个独立的功能,而不是一种方法,请参阅其他答案。