【发布时间】:2020-06-01 10:46:04
【问题描述】:
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 怎么会起作用?
【问题讨论】:
-
你正在尝试调用
operator==,它不是为你生成的,所以你一定是写了但没有显示。有一个内置的指针相等运算符。 -
根据我的经验,最好让赋值运算符自我赋值安全而不是针对病态情况进行优化。
标签: c++ class operator-overloading