对于一些人来说这可能是显而易见的,但我真的无法绕过它
在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。
我怎么可能解决这个问题?感谢
答案 0 :(得分:-1)
==operator
定义为friend function,如下所示。那么你就不需要再使用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;
}
评论: