【问题标题】:Code errors at no operator overload没有运算符重载的代码错误
【发布时间】:2018-03-14 00:51:45
【问题描述】:

我有一个类使用 std::vector> 来指示物品及其数量(可以有多个包含相同物品的库存物品)。

然后我开始重载 clsInventoryItem 的 == 运算符。 设置最终是: clsInventory.cpp -> 包括:clsInventory.h clsInventory.h -> 包括:clsInventoryItem.h clsInventoryItem.h -> 包括:stdafx.h(它又包括项目的其余部分,不包括那两个头文件)

clsInventoryItem 在其头文件中包含以下内容:

class clsInventoryItem
{
public:
    clsInventoryItem( clsItem* Item, char Quality );
    clsItem* GetItem( );
    char GetQuality( );

    inline bool operator==( const clsInventoryItem& other )
    { /* do actual comparison */
        if (m_Item == other.m_Item
             && m_Quality == other.m_Quality)
        {
            return true;
        }
        return false;
    }
private:
    clsItem* m_Item;
    char m_Quality;
};

而且还是报了一个equals函数没有重载的错误("Severity Code Description Project File Line Suppression State 错误 C2678 二进制“==”:未找到采用“const BrawlerEngineLib::clsInventoryItem”类型的左侧操作数的运算符(或没有可接受的转换)BrawlerEngineLib d:\program files (x86)\microsoft visual studio\2017 \community\vc\tools\msvc\14.10.25017\include\utility 290 “)... 任何人都知道为什么会出现这种情况,以及如何解决它?

【问题讨论】:

  • 它仍然给出一个等于函数没有重载的错误请编辑你的问题并添加确切的错误消息的文本。如果这是 Visual Studio,则从“输出”选项卡复制错误。
  • 您不应在标题中包含stdafx.h。 stdafx.h 的包含必须是源文件的第一个非注释行。 #include "stdafx.h" 以上的所有行都被编译器忽略。
  • if (m_Item == other.m_Item -- 您正在比较指针值。当然不应该使用m_Item 的指针值来查看两个clsItem 对象是否相等。
  • bool operator==() 函数应该是 const。
  • 如果您还没有,问问自己,“谁负责管理m_Item?”

标签: c++ operator-overloading operator-keyword equals-operator


【解决方案1】:

您的 inline bool operator==(const clsInventoryItem& other) 预计为 const。
要解决此问题,您需要将 inline bool operator==(const clsInventoryItem& other) 更改为 inline bool operator==(const clsInventoryItem& other) const

另外,你可以去掉关键字inline,现代编译器会忽略这个关键字,而旧的编译器只使用它作为提示,并自行决定是否内联函数。他们很擅长;-)

【讨论】:

  • @JoeyvanGangelen 没问题,很高兴它有帮助! :-)
猜你喜欢
  • 1970-01-01
  • 2015-06-24
  • 1970-01-01
  • 2015-06-20
  • 2013-11-14
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多