【问题标题】:c++ comparing to NULL after overloading == operatorc++ 在重载 == 运算符后与 NULL 进行比较
【发布时间】: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 内的材质返回类型函数。在该函数中,我搜索是否有任何元素具有相同的名称和如果不是,我返回一个空值。因为上面的例子给出了完全相同的错误,而且因为我的代码很乱,所以我没有在问题中包含链表代码。

标签: c++ operator-overloading


【解决方案1】:

喜欢@Fei Xiang 的评论使它成为一个非成员函数。在这里,您可以将==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;
}

评论:

  1. 使用constructors and member initializer lists(如上)。
  2. 对参数和类成员变量使用不同的名称是一种很好的做法。

【讨论】:

  • 这并没有回答问题,它只是稍微重构了代码。 getName() 在原始情况下也不需要
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-08
  • 2015-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多