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

我做错了什么?

4

2 回答 2

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;
}
于 2012-05-26T18:00:17.113 回答
0

它不必对重载做任何事情(好吧,也许有点)。

这个说法

stream << statemap[m_currentstate];

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

[你也必须在 statemap 类中重载 <<。]

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

于 2012-05-26T18:00:17.267 回答