如何使用在子构造函数

时间:2015-11-07 06:06:27

标签: c++ constructor

我有一个子类知道发送父类的对象类型,但我无法弄清楚如何创建它,以便父级可以保留对象而不在父类构造函数中创建额外的副本。

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()){};
}

正确的方法是什么?

我不知道如何尝试这样做以确定它是否正常,因为它可能会在一段时间内正常工作,即使内存无效也无法使用。

1 个答案:

答案 0 :(得分:1)

不是在堆栈内存中创建对象,而是使用堆内存创建一个对象。父母可以拥有该对象。

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()){};
}
相关问题