What is the best way to replace or substitute if..else if..else trees in programs?

后端 未结 21 1142
迷失自我
迷失自我 2020-11-28 06:23

This question is motivated by something I\'ve lately started to see a bit too often, the if..else if..else structure. While it\'s simple and has its uses, somet

21条回答
  •  借酒劲吻你
    2020-11-28 07:19

    Depending on the type of thing you are if..else'ing, consider creating a hierarchy of objects and using polymorphism. Like so:

    class iBase
    {
       virtual void Foo() = 0;
    };
    
    class SpecialCase1 : public iBase
    {
       void Foo () {do your magic here}
    };
    
    class SpecialCase2 : public iBase
    {
       void Foo () {do other magic here}
    };
    

    Then in your code just call p->Foo() and the right thing will happen.

提交回复
热议问题