c ++错误C2662不能将'this'指针从'const Type'转换为'Type&'

c ++错误C2662不能将'this'指针从'const Type'转换为'Type&'

问题描述:

我试图重载c ++操作符==但是得到一些错误...

I am trying to overload the c++ operator== but im getting some errors...

错误C2662:'CombatEvent :: getType':无法转换'this 'const CombatEvent'指向'CombatEvent&'

error C2662: 'CombatEvent::getType' : cannot convert 'this' pointer from 'const CombatEvent' to 'CombatEvent &'

此错误在此行

if (lhs.getType() == rhs.getType())

查看下面的代码:

class CombatEvent {

public:
    CombatEvent(void);
    ~CombatEvent(void);

    enum CombatEventType {
        AttackingType,
        ...
        LowResourcesType
    };

    CombatEventType getType();
    BaseAgent* getAgent();

    friend bool operator<(const CombatEvent& lhs, const CombatEvent& rhs) {

        if (lhs.getType() == rhs.getType())
            return true;

        return false;
    }

    friend bool operator==(const CombatEvent& lhs, const CombatEvent& rhs) {

        if (lhs.getType() == rhs.getType())
            return true;

        return false;
    }

private: 
    UnitType unitType;
}

可以帮助吗?

CombatEventType getType();

需要

CombatEventType getType() const;

您的编译器抱怨,因为函数被赋予 const 对象,你试图调用一个非 - const 函数。当一个函数获得一个 const 对象时,对它的所有调用必须在整个函数中都是 const 不确定它没有被修改)。

Your compiler is complaining because the function is being given a const object that you're trying to call a non-const function on. When a function gets a const object, all calls to it have to be const throughout the function (otherwise the compiler can't be sure that it hasn't been modified).