【问题标题】:Creating a child class based on external settings根据外部设置创建子类
【发布时间】:2020-09-30 06:51:02
【问题描述】:

我认为我的问题与对象切片有关。

我有以下课程:

class Base{
public:
    virtual int do_Something();
}

class ChildA : public Base {
public:
    int do_Something();    // ChildA does something
}

class ChildB : public Base {
public:
    int do_Something();    // ChildB does something
}

在我的main.cpp 中,我想根据用户设置的特定配置创建一个对象 ChildA() 或 ChildB()。
例如,我可以想象的(非常丑陋的)方式是:

int config = 1; // selected by the user

Base *base;
if (config==0){
    ChildA child = (ChildA)base;
}
else if (config==1){
    ChildB child = (ChildB)base;
}

child->doSomething();

这有意义吗?有什么更好的方法来做到这一点?

【问题讨论】:

  • C++ 不是 Java;因此,除非您要求,否则您没有指针。

标签: class oop c++11 inheritance


【解决方案1】:

从不同的答案中,我发现一个明智的方法是:

int config = 1; // selected by the user

Base *base;
if (config==0){
    base = new ChildA();
}
else if (config==1){
    base = new ChildB();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 2017-12-09
    • 1970-01-01
    相关资源
    最近更新 更多