【发布时间】: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