gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:59:20 25 4
gpt4 key购买 nike

我有一个子类,它知道要向父类发送什么类型的对象,但我不知道如何创建它,以便父类可以保留该对象,而无需在父类构造函数中制作额外的拷贝。

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++ - 如何使用在子构造函数中创建的对象构造父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33579722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com