2015-11-07 144 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

相關問題