【发布时间】:2018-08-27 08:46:17
【问题描述】:
这对某些人来说可能很明显,但我真的无法绕过它
在Material里面我重载了==操作符:
`
class
Material{
int id;
int count;
double price;
string name;
Material() {
}
Material(int id) {
this->id = id;
}
Material(int id,int count,double price,string name) {
this->id = id;
this->count = count;
this->name = name;
this->price = price;
}
string getName() {
return name;
}
bool operator==(Material& obj)
{
if (this->name == obj.getName())return true;
else return false;
}`
每当我做类似的事情时:if(obj ==NULL){...}
程序停止并抛出异常。
TradingVendors.exe 中的 0x0F61D6F0 (ucrtbased.dll) 引发异常:0xC0000005:访问冲突读取位置 0x00000000。
我怎么可能解决这个问题?谢谢
【问题讨论】:
-
minimal reproducible example 请。特别是包括任何构造函数,如果你有的话。
-
最好将
operator==实现为非成员函数,以允许对两个操作数进行更多封装和隐式转换。此外,您应该使用 const 引用。 -
您无法检查对对象的引用是否为 NULL。
-
@Raindrop7 我真正在做的是将一个对象的名称传递给位于linkedlist
内的材质返回类型函数。在该函数中,我搜索是否有任何元素具有相同的名称和如果不是,我返回一个空值。因为上面的例子给出了完全相同的错误,而且因为我的代码很乱,所以我没有在问题中包含链表代码。