C ++-运算符=自赋值检查

奇怪的
class Person {
private:
    string name;
    int id;

public:
    Person(string name, int id): name(name), id(id) {}
    const Person& operator=(const Person &another) {
        if (*this == another) // What is the problem here?
            return *this;
        // do copy
        return *this;
    }
};

我想做一个operator =重载函数。在自我分配检查中,如果执行上述检查,将显示错误提示Invalid operands to binary expression (Person and const Person)但是,如果执行此操作this == &another,则不会显示任何错误。
错误说的类型this和类型another不同吗?但是,如果是这样,怎么this == &another会起作用?

罗威

*this == another尝试检查两个对象是否具有相同的值。为此,您必须定义operator==for Person也就是说,Person::operator==()将确定两个Person对象是否具有相同的

但是,由于您要防止自我分配,因此您真正需要的是比较两个对象身份,而不是它们的价值您可以通过比较它们在内存中的地址来实现,即:

if (this == &another) // Is "another" the same object?
   return *this; // skip assignment

对此的操作数operator==是指向的指针Person,而不是Person对象。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章