Dynamic_Cast 在 C++ 中

Dynamic_Cast in C++

通过适当的 OOD,我很少需要使用 dynamic_cast,但我在以下示例中使用它。这是正确的方法吗? Long 和 Double 类 是数字的代码的想法,我希望能够添加数字,包括 Double 和 Long 的混合,如 main() 中所示。

class Numeric{
  virtual Numeric& (const Numeric& num)=0;
 }

class Double: public Numeric{
   double data;
   Numeric& operator+(const Numeric& num){
     //if Double type
     if(Double* d = dynamic_cast<Double *>(num)){
         return Double(data+(Double &)num.data);
       }
     else{  //must be Long
         return (doLongDoubleMath());
       }
    }
 }
 class Long: public Numeric{
  long data;
   Numeric& operator+(const Numeric& num){
   }
 }

  int main(){
    Numeric &n1 = Double(1.1);
    Numeric &n2 = Long(10);
    Numeric &result = n1+n2;

   return 0;
   }

我希望能够混合使用不同的类型,例如添加 Double 和 Long..等,Dynamic_cast 这样做是正确的方法吗,或者您能想到更好的方法吗?

问题是,您需要对两个 个对象而不是一个对象进行多态。动态转换是解决这个问题的一种方法,但我认为还有更好的方法:double dispatch:

class Foo;
class Bar;
class Base {
    public:
        virtual Base& operator+(const Base& other) = 0;

    protected:
        virtual Base& addTo(Foo& other) const = 0;
        virtual Base& addTo(Bar& other) const = 0;
}
class Foo : public Base {
    public:
        virtual Base& operator+(const Base& other) {
            return other.addTo(*this);
        }
}
...

当然,这意味着您必须编写 N^2 addTo() 函数,其中 N 是您希望能够添加的 类 的数量可互换地。但这与您需要编写的 if(Foo& foo = dynamic_cast<Foo&>(other)) {...} 子句的数量相同。

而且双重分派可能更快,因为您的 else if() 梯形图会多次检查其他对象的类型,而虚函数调用只会跟随 vtable 指针一次调用正确的函数。