在 C++ 中,当需要检查两个对象是否相等时,通常会使用运算符“==”进行比较。然而在某些情况下,使用默认的“==”运算符比较操作并不能得出正确的结果。这是因为对于用户自定义的类型,C++ 必须在运行时决定使用哪个 “==” 运算符,以此解决不同类型之间的重载问题。
一种常用的解决方法是手动添加一个重载的“==”运算符来覆盖默认的实现。例如,假设我们有一个自定义的 Person 类型:
class Person {
public:
Person(int age, const std::string& name)
: age_(age), name_(name) {}
bool operator==(const Person& other) const {
return age_ == other.age_ && name_ == other.name_;
}
private:
int age_;
std::string name_;
};
现在,我们可以使用“==”运算符比较两个 Person 对象的属性。例如:
Person john(22, "John");
Person john_clone(22, "John");
if (john == john_clone) {
std::cout << "John and John Clone are the same person!" << std::endl;
}
在上面的示例中,我们重载了“==”运算符,以便可以将两个 Person 对象进行比较。
此外,在 C++11 中,可以使用“= default”语法来声明编译器默认生成的运算符。这样,编译器将在编译时自动决定如何重载运算符。例如:
class Foo {
public:
Foo() = default; // Declare default constructor
Foo(const Foo&) = default; // Declare copy constructor
Foo(Foo&&) = default; // Declare move constructor
Foo& operator=(const Foo&) = default; // Declare copy assignment operator
Foo& operator=(Foo&&) = default; //