C++ how to replace constructor switch?

后端 未结 4 2070
执念已碎
执念已碎 2021-01-23 05:07

I would like to replace big switch with something more elegant.

class Base
{
public:
  Base(void*data, int size);
  virtu         


        
4条回答
  •  轮回少年
    2021-01-23 05:43

    You can use a simple factory method to create objects by required type and constructor parameters as in following example. Don't forget the virtual destructor when using inheritance and virtual functions.

    #include 
    
    class Base
    {
    public:
        Base(void* data, int size) {};
        virtual ~Base() {}
        virtual void Something() = 0;
    };
    
    class A : public Base
    {
    public:
        A(void* data, int size) : Base(data, size) {}
        void Something() override {};
    };
    
    class B : public Base
    {
    public:
        B(void* data, int size) : Base(data, size) {}
        void Something() override {};
    };
    
    Base* MyFactory(char type, void* data, int size)
    {
        switch (type)
        {
            case 'a': return new A(data, size);
            case 'b': return new B(data, size);
            default:
                return nullptr;
        }
    }
    
    int main()
    {
        std::unique_ptr obj1(MyFactory('a', nullptr, 1));
        obj1->Something();
        std::unique_ptr obj2(MyFactory('b', nullptr, 1));
        obj2->Something();
    }
    

提交回复
热议问题