c ++错误C2662不能将'this'指针从'const Type'转换为'Type&' [英] c++ error C2662 cannot convert 'this' pointer from 'const Type' to 'Type &'

查看:570
本文介绍了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).

这篇关于c ++错误C2662不能将'this'指针从'const Type'转换为'Type&amp;'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆