如何使用在子构造函数中创建的对象构造父类

How to construct a parent class with an object created in the child constructor

本文关键字:对象 父类 创建 何使用 构造函数      更新时间:2023-10-16

我有一个子类,它知道向父类发送什么类型的对象,但我不知道如何创建它,这样父类就可以在不在父类构造函数中制作额外副本的情况下保留对象。

class Thing {
...some stuff...
};
class Parent {
private:
  Thing & thing;
public:
  Parent(Thing & in_thing):thing(in_thing);
};
class Child : public Parent {
  public:
    // Does my Thing object get created on the stack here and therefor I can't keep a reference or pointer to it in the parent class?
    Child():Parent(Thing()){};
}

做这件事的正确方法是什么?

我不知道该如何尝试,看看它是否正常,因为即使内存无法使用,它也可能在一段时间内正常工作。

与其在堆栈内存中创建对象,不如使用堆内存创建一个对象。父对象可以拥有该对象。

class Parent {
  private:
    std::unique_ptr<Thing> thing;;
  public:
    Parent(Thing* in_thing): thing(in_thing);
};

class Child : public Parent {
  public:
    Child():Parent(new Thing()){};
}

使用指针还允许Child创建Thing的子类型。有时你需要它。

class ChildThing : public Thing { ... };
class Child : public Parent {
  public:
    Child():Parent(new ChildThing()){};
}