C++中的多态相等性

3
如果我在C++中将一个基本类型与一个更派生的类型进行比较,operator==是否只应该比较基本类型部分,还是如果传递了更派生的类型,它应该返回false?
例如:
BaseType myBase("a", "b");
DerivedType myDerived("a", "b", "c");

myDerived == myBase // This should return false, right ?
myBase == myDerived // Should this return false as well ? How can the BaseType operator know that it's parameter is derived ?

我认为这两个语句都应该返回false,但我不确定如何实现基本类型的operator==


2
如何实现运算符完全由您决定。但是,BaseType 运算符无法从 DerivedType 检查任何内容,因为通常基类不知道可能的派生类。当然,除非您使用正确的参数将运算符实现为独立函数来处理两种类型。 - Some programmer dude
我不确定你所说的“将运算符实现为独立函数”的意思是什么。基础类型如何能够检查它与派生类型的差异? - Willem D'Haeseleer
@WillemD'haeseleer 如果你需要检查类型是否不同,那么你就不再使用多态性了。 - juanchopanza
1个回答

0

既然你在询问多态相等性,那么通过 BaseType 的公共接口进行多态比较是有意义的。例如:

struct BaseType
{
  virtual int foo() const { return 42; }
};

struct DerivedType : BaseType
{
  virtual int foo() const { return i_; }
  explicit DerivedType(int i) : i_(i) {}
 private:
  int i_;
};

bool operator==(const BaseType& lhs, const BaseType& rhs)
{
  return lhs.foo() == rhs.foo();
}

int main()
{
  BaseType b;
  DerivedType d(13);
  std::cout << std::boolalpha;
  std::cout << (b == d) << std::endl;
}

有不同的实现方式,但基本思路是等号运算符使用操作数的虚拟公共接口。但公共接口可能会隐藏很多逻辑,例如通过成员函数。

bool equals(const BaseType& other) const
{
  // Call virtual methods to determine equality.
  // These can be public, private or protected.
}

非成员运算符然后调用此函数:

bool operator==(const BaseType& lhs, const BaseType& rhs)
{
  return lhs.equals(rhs);
}

如果foo()是hash_content(),并且返回类型足够大,它实际上可以用于此目的。 - Balog Pal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接