如何使用在子构造函数中创建的对象构造父类
How to construct a parent class with an object created in the child 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()){};
}
做这件事的正确方法是什么?
我不知道该如何尝试,看看它是否正常,因为即使内存无法使用,它也可能在一段时间内正常工作。
与其在堆栈内存中创建对象,不如使用堆内存创建一个对象。父对象可以拥有该对象。
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()){};
}
相关文章:
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将父类对象强制转换为子类的问题
- C++ 将子类的对象添加到父类的向量中
- 对静态分配的子类对象进行静态分配的纯虚拟父类引用是否合法?
- 具有纯虚函数和指针数组对象类型的父类的指针数组
- 使用父类实例化的向下转换对象
- 对象在称为指向父类的指针时会丢失其成员的数据
- 检查哪个子类是父类对象
- 将对象强制转换为派生类以访问父类的受保护成员
- 如何仅通过父类对象限制对象创建
- 当函数返回类型为父类时,如何返回子类的对象?
- 调用实际对象而不是父类的方法
- C++:使用父类运算符函数更新子类对象的继承变量
- 比较从父类继承但存储在父类的向量中的类的对象类型
- 在C++对象中:我应该使用父类强制转换指针,还是应该使用实际类本身进行强制转换
- 强制转换为父类对象而不是引用时会出现哪些不良结果
- C++中包含父类对象的子类有什么问题(如果有的话)
- 将对象传递到同一父类的数组中
- 带模板的继承(访问子类成员函数内父类的变量和对象)