【问题标题】:c++ error C2662 cannot convert 'this' pointer from 'const Type' to 'Type &'c++错误C2662无法将'this'指针从'const Type'转换为'Type &'
【发布时间】:2012-08-17 14:12:23
【问题描述】:

我正在尝试重载 c++ operator== 但我遇到了一些错误...

错误 C2662:“CombatEvent::getType”:无法将“this”指针从“const CombatEvent”转换为“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;
}

有人可以帮忙吗?

【问题讨论】:

    标签: c++ operator-overloading syntax-error friend-function


    【解决方案1】:
    CombatEventType getType();
    

    需要

    CombatEventType getType() const;
    

    您的编译器正在抱怨,因为该函数被赋予了一个const 对象,而您试图在该对象上调用一个非const 函数。当函数获得const 对象时,在整个函数中对其的所有调用都必须是const(否则编译器无法确定它没有被修改)。

    【讨论】:

      【解决方案2】:

      将声明更改为:

      CombatEventType getType() const;
      

      您只能通过对 const 的引用调用“const”成员。

      【讨论】:

        【解决方案3】:

        这是一个 const 问题,您的 getType 方法未定义为 const,但您的重载运算符参数是。因为 getType 方法不能保证它不会更改类数据,所以编译器会抛出错误,因为您无法更改 const 参数;

        最简单的改变就是把getType方法改成

        CombatEventType getType() const;
        

        当然,除非方法实际上是在改变对象。

        【讨论】:

          【解决方案4】:

          我已经看到类似代码的错误

              get_color(const std::unsigned_integral auto &x,
                        const std::unsigned_integral auto &y,
                        const BPPT &                       depth,
                        const std::unsigned_integral auto &palette    = 0U,
                        const std::unsigned_integral auto &texture_id = 0U) const
          

          当我更改为模板时,它起作用了。

            template<std::unsigned_integral xT,
                     std::unsigned_integral yT,
                     std::unsigned_integral paletteT,
                     std::unsigned_integral texture_idT>
            [[nodiscard]] Color16
              get_color(const xT          x,
                        const yT          y,
                        const BPPT        depth,
                        const paletteT    palette    = 0U,
                        const texture_idT texture_id = 0U) const
          

          【讨论】:

            猜你喜欢
            • 2020-08-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-12-17
            • 2013-11-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多