避免重复dynamic_cast的最佳方法?

时间:2016-11-22 06:38:37

标签: c++ dynamic-cast

我有像

这样的情况
Shape *shape =dynamic_cast<Shape*>(obj);

if(dynamic_cast<Rectangle*>(obj))
{
   func();
   Rectangle* obj1 = dynamic_cast<Rectangle*>(obj);
   obj1->DoSomething1();
   obj1->DoSomething2();
}
else if(dynamic_cast<Circle*>(obj))
{
   func();
   Cirlce* obj2 = dynamic_cast<Cirlce*>(obj);
   obj1->DoSomething3();
   obj1->DoSomething4();
}
else if(dynamic_cast<Blah*>(obj))
{
   func();
   Blah* obj1 = dynamic_cast<Blah*>(obj);
   obj1->DoSomething5();
   obj1->DoSomething6();
}
...
...

避免在dynamic_cast语句中再次调用if/else并为该特定对象类型执行方法的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

一般来说,你应该避免使用这种结构,并按照预期的方式使用多态,例如:

class Shape
{
public:
    virtual void DoSomething() = 0;
};

class Rectangle : public Shape
{
public:
    void DoSomething()
    {
        DoSomething1();
        DoSomething2();
    }
};

class Circle : public Shape
{
public:
    void DoSomething()
    {
        DoSomething3();
        DoSomething4();
    }
};

class Blah : public Shape
{
public:
    void DoSomething()
    {
        DoSomething5();
        DoSomething6();
    }
};

Shape *shape = dynamic_cast<Shape*>(obj);
if (shape)
{
    func();
    shape->DoSomething(); 
}

如果这不是您的代码的选项,您可以执行以下操作以删除重复的dynamic_cast来电,至少:

if (Rectangle *r = dynamic_cast<Rectangle*>(obj))
{
    func();
    r->DoSomething();
}
else if (Circle *c = dynamic_cast<Circle*>(obj))
{
    func();
    c->DoSomethingElse();
}
else if (Blah *b = dynamic_cast<Blah*>(obj))
{
    func();
    b->DoSomethingElseElse();
}