2015-11-07 142 views
0

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

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

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

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

我假设你不能在子类初始化列表中调用new - 你有什么可以和不可以去初始化列表的规则的链接吗?你不能在那里放置任意代码,对吧? – xaxxon

+1

@xaxxon。表达式newThing()用作初始化基类“Parent”的参数。任何可以转换为“Thing *”的表达式在那里都是有效的。这与初始化列表中的内容不同。您只能在初始化列表中使用基类和成员。但是用来初始化它们的值可以是任何有效的表达式。 –

+0

所以我可能会调用一些返回对象的静态方法?像'Thing :: create_thing()'(如果存在)?这有多远?我可以说'rand()> 5吗?新事物(0):新事物(1)'? – xaxxon

相关问题