C++ 如何在switch语句中正确初始化不同的派生类?

C++ 如何在switch语句中正确初始化不同的派生类?,c++,pointers,inheritance,abstract,dynamic-memory-allocation,C++,Pointers,Inheritance,Abstract,Dynamic Memory Allocation,我有以下代码,具有基类base的类层次结构,以及几个派生类Derived1、Derived2、Derived3…等等 switch(i){ case 1:{ Derived1* d1; generateD1(d1); otherFunc(d1); //function signature is otherFunc(Base*) break; } case 2:{ Derived2* d2;

我有以下代码,具有基类base的类层次结构,以及几个派生类Derived1、Derived2、Derived3…等等

switch(i){
    case 1:{
        Derived1* d1;
        generateD1(d1);
        otherFunc(d1); //function signature is otherFunc(Base*)
        break;
    }
    case 2:{
        Derived2* d2;
        generateD2(d2);
        otherFunc(d2);
        break;
    }
    ...  //goes on for many cases
}
如何使用继承机制来改进上述代码?

类似这样的内容:

class Base
{
    public:
        virtual ~Base() {}

        virtual void generate() = 0 {}

        virtual void other() = 0 {}
};

class Derived1 : public Base
{
    public:
        virtual void generate() override {}

        virtual void other() override {}
};

class Derived2 : public Base
{
    public:
        virtual void generate() override {}

        virtual void other() override {}
};

int main()
{
    int i;
    Base *b;
    switch(i)
    {
        case 1:
            b = new Derived1;
            break;
        case 2:
            b = new Derived2;
            break;
        ...
    }
    b->generate();
    b->other();
    ...
    delete b;
    return 0;
}

您可以放弃
generate()
方法,只使用构造函数:

class Base
{
    public:
        virtual ~Base() {}

        virtual void other() = 0 {}
};

class Derived1 : public Base
{
    public:
        Derived1() {}

        virtual void other() override {}
};

class Derived2 : public Base
{
    public:
        Derived2() {}

        virtual void other() override {}
};

int main()
{
    int i;
    Base *b;
    switch(i)
    {
        case 1:
            b = new Derived1;
            break;
        case 2:
            b = new Derived2;
            break;
        ...
    }
    b->other();
    ...
    delete b;
    return 0;
}

仅供参考,除了@SidS的解决方案外,我们还可以将生成过程提取为一个简单函数,该函数返回一个
Base
指针,如下所示。 在这里,我还使用了
std::unique\u ptr
,这使得我们的代码在RAII语义中更加安全,然后您可以省略调用
delete b

#include <stdexcept>
#include <memory>

std::unique_ptr<Base> create(int i) // C++11
{
    switch(i)
    {
        case 1:
            return std::make_unique<Derived1>(); // C++14
            break;
        case 2:
            return std::make_unique<Derived2>();
            break;
        default:
            throw std::logic_error("unsupported.");
    }
}

谁说答案一定是某种继承?根据所有相关因素,这也可以通过使用模板来“改进”。或是当今使用的最复杂的通用编程语言C++中的许多其他技术中的任何一种都是可用的。“改进”所示示例的最佳方法在很大程度上取决于除所示的小代码段之外的所有其他内容。这对于一个聪明的答案来说是不够的。除了其他答案之外,教授良好的实践是非常重要的。谢谢你的答案。如果我的“otherFunc”是另一个类的成员函数,它接受一个基指针作为参数,并且所有派生函数都需要由同一个函数调用,该怎么办?我不太明白你的问题,但我认为你应该把它作为一个新问题发布。
auto b = create(i);
b->generate();
b->other();