gpt4 book ai didi

c++ - operator== 在 C++ 中使用双重分派(dispatch)

转载 作者:太空狗 更新时间:2023-10-29 20:18:41 24 4
gpt4 key购买 nike

应该如何实现

operator==(const Base& base)

比较子类 s.t.当调用为

时,调用将被正确调度
Base* base1 = new Derived1();
Base* base2 = new Derived2();
base1->operator==(*base2)?

最佳答案

  1. 将 operator== 作为独立函数实现。
  2. 让它在其中一个参数上调用虚方法(例如 IsEqual())

这让你到达了你拥有的地步

Derived1::IsEqual(const Base& base)

打电话。从这里你有一些选择

  1. 使用 RTTI dynamic_cast<> base 到 Derived1
  2. 如果派生的数量少且有限,可以实现

    virtual bool Base::IsEqualToDerived(const Derived1& d) {return false};
    virtual bool Base::IsEqualToDerived(const Derived2& d) {return false};

作为虚拟方法。在 Derived1 中,您重写并进行真实比较。

关于c++ - operator== 在 C++ 中使用双重分派(dispatch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3352765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com