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] 删除。
我来说两句