我还是 C++ 的新手(一般编程),如果这个问题很愚蠢或被问过很多次,请原谅我。这是问题..假设在同一个类下有两个对象 A 和 B。
例如
class Fruit{
int apple;
int banana;
fruit(int x, int y){
apple=x;
banana=y;
}
}
Fruit A(1,1);
Fruit B(1,1);
Run Code Online (Sandbox Code Playgroud)
如果我想检查对象 A 的内容是否与对象 B 的内容相同,我是否必须比较从 A 到 B 的每个变量,或者
if(Object A == Object B)
return true;
Run Code Online (Sandbox Code Playgroud)
会做这份工作吗?
if(Object A == Object B)
return true;
Run Code Online (Sandbox Code Playgroud)
会做这份工作吗?不,它不会,它甚至不会编译
错误:“operator==”不匹配(操作数类型为“Fruit”和“Fruit”)
你需要实现一个比较operator==,比如
bool Fruit::operator==(const Fruit& rhs) const
{
return (apple == rhs.apple) && (banana == rhs.banana);
// or, in C++11 (must #include <tuple>)
// return std::tie(apple, banana) == std::tie(rhs.apple, rhs.banana);
}
Run Code Online (Sandbox Code Playgroud)