C++ c++;重载==运算符后与NULL比较
这对一些人来说可能是显而易见的,但我真的无法回避 内部C++ c++;重载==运算符后与NULL比较,c++,operator-overloading,C++,Operator Overloading,这对一些人来说可能是显而易见的,但我真的无法回避 内部MaterialI重载==运算符: ` 当我做类似的smth时:if(obj==NULL){…} 程序停止并抛出异常 TradingVendors.exe中0x0F61D6F0(ucrtbased.dll)处引发异常:0xC0000005:访问冲突读取位置0x00000000 我怎么可能解决这个问题?谢谢喜欢@Fei Xiang的评论,将其作为非会员功能。在这里,您可以定义==运算符,如下所示。这样您就不需要再使用getName() clas
Material
I重载==运算符:
`
当我做类似的smth时:if(obj==NULL){…}
程序停止并抛出异常
TradingVendors.exe中0x0F61D6F0(ucrtbased.dll)处引发异常:0xC0000005:访问冲突读取位置0x00000000
我怎么可能解决这个问题?谢谢喜欢@Fei Xiang的评论,将其作为非会员功能。在这里,您可以定义
==运算符
,如下所示。这样您就不需要再使用getName()
class Material
{
private:
int id;
int count;
double price;
std::string name;
public:
Material()
:id(0), count(0),price(0.00), name("unknown")
{}
Material(const int& id)
:id(id)
{}
Material(const int& id, const int& count, const double& price,
const std::string& name)
{ // use initializer list instead
this->id = id;
this->count = count;
this->name = name;
this->price = price;
}
//const std::string& getName()const { return name; }
friend bool operator== (const Material& obj1, const Material& obj2);
};
bool operator== (const Material& obj1, const Material& obj2)
{
return (obj1.name == obj2.name)? true: false;
}
评论:
请如果有构造函数,请特别包括它们。请检查:最好将
操作符==
实现为非成员函数,以便在两个操作数上进行更多的封装和隐式转换。另外,您应该使用常量引用。您无法检查对对象的引用是否为NULL。@Raindrop7我真正做的是将一个对象的名称传递给linkedlist中的材质返回类型函数。在该函数中,我搜索是否有任何元素具有相同的名称,如果没有,我将返回NULL。因为上面的例子给出了完全相同的错误,而且因为我的代码凌乱,我没有在问题中包含linkedlist代码。这并没有回答问题,它只是稍微重构了代码。原始情况下也不需要getName()
class Material
{
private:
int id;
int count;
double price;
std::string name;
public:
Material()
:id(0), count(0),price(0.00), name("unknown")
{}
Material(const int& id)
:id(id)
{}
Material(const int& id, const int& count, const double& price,
const std::string& name)
{ // use initializer list instead
this->id = id;
this->count = count;
this->name = name;
this->price = price;
}
//const std::string& getName()const { return name; }
friend bool operator== (const Material& obj1, const Material& obj2);
};
bool operator== (const Material& obj1, const Material& obj2)
{
return (obj1.name == obj2.name)? true: false;
}