c++ - 如何根据构造函数参数用父类(super class)类型初始化成员变量?

标签 c++ pointers inheritance member

搜索了几个小时后,我终于来到了这里。我有一个 Container 类,它带有一个指向 Base 类的指针作为成员变量。这应该是指 Spec1 或其他继承的 Base 类,我在这里省略了。类型应由构造函数中的参数确定(例如字符串、枚举、整数等)。

我读了很多关于动态内存分配的文章以及为什么应该尽可能避免它。可以避开这里吗?构造函数后没有销毁任何普通对象吗?还是设计思路完全错误?我来自 Java :( 提前致谢。

class Base{
  public:
    virtual ~Base(){}; // required?
    virtual void doSomething() = 0;
};

class Spec1 : public Base {
     public:
       Spec1(){};
       Spec1(int i){
         // whatever
       }
       void doSomething(){
          std::printf("hello world");
       }
};

class Container{
   public:
     Container(String type_message){
      if (type_message.compare("We need Spec1")){
          m_type = new Spec1(1);
      } // add more ifs for other types (Spec2, Spec3 etc.)
     }
     void doSomethingWithSpec(){
        m_type->doSomething();
     }
   private:
      Base* m_type;
 };

int main (int argc, char **argv){
    Container a ("We need Spec1");
    a.doSomething();
}

最佳答案

要求 Container 了解 Base 的每个可能的派生类,这听起来不是一个好的设计。这就是工厂功能的用途。

Container 将该对象存储为 std::unique_ptr 以避免内存泄漏和手动内存管理。

struct Base {
    virtual ~Base() = default;
    virtual void doSomething() = 0;
};

struct Spec1 : Base {
    void doSomething() override {
        std::printf("%s\n", __PRETTY_FUNCTION__);
    }
};

// Factory function.
std::unique_ptr<Base> createBase(std::string const& type) {
    if(type == "Spec1")
        return std::unique_ptr<Base>(new Spec1);
    throw std::runtime_error("Unknown type " + type);
}

class Container {
    std::unique_ptr<Base> m_type;
public:
    Container(std::string const& type)
        : m_type(createBase(type))
    {}

    void doSomething(){
        m_type->doSomething();
    }
};

int main() {
    Container a ("Spec1");
    a.doSomething();
}

关于c++ - 如何根据构造函数参数用父类(super class)类型初始化成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50608269/

相关文章:

javascript继承函数导致jquery错误

c# - 派生类型和泛型

c++ - 如何用类实现多级继承

C++:将代码重定向到特定位置

c - 纯 C : Copy rows and columns of a 2D array using pointers

c++ - Printf() - 打印字符限制

c++ - 通过引用传递数组与传递指针的函数参数绑定(bind)规则

c++取消引用通过引用传递分配的指针,给出随机值

c++ - 将字符串的 UNIX 行结尾转换为 DOS 行结尾

c++ - 并行算法产生一个集合的所有可能序列