2010-02-27 11 views
2

我有一個Board類,其中構造函數將板的尺寸作爲參數。我也有一個Puzzle類,它擁有一些片段,我希望它有一個Board作爲數據成員。我想這樣,所以當我創建一個Puzzle的實例時,我將創建我的實例Board,因此我不必將用戶作爲單獨的實例。然而,當我在Puzzle.h文件中聲明的板,它需要一個實際數目爲Board構造:是否有可能將類的實例作爲另一個類的數據成員?

// Puzzle.h file 

private: 
    Board theBoard(int height, int width); // Yells at me for not having numbers 

有沒有辦法有一個類的對象是另一個類,如果該對象的數據成員尚未創建?

回答

6

如果我理解正確的,問題是,你需要正確實例化板:

class Puzzle { 
public: 
     Board theBoard; 

     Puzzle(int height, int width) : theBoard(height, width) // Pass this into the constructor here... 
     { 
     }; 
}; 
+0

是的,它做到了。我首先嚐試這樣做,而不使用初始列表。爲什麼初始化程序列表會有所作爲?謝謝。 – Isawpalmetto 2010-02-27 23:12:48

+0

構造函數運行時,所有成員都需要直接初始化。你可以使用默認的初始化,但是如果你沒有使用指針,並且沒有默認的構造函數,你需要一個初始化列表來構造這些對象。 – 2010-02-27 23:23:02

1

您必須聲明的數據成員沒有指定任何超過類型,然後用特殊的初始化構造函數初始化列表語法。一個例子將是更加清晰:

class A 
{ 
    int uselessInt; 
    public: 
    A(int UselessInt) 
    { 
     uselessInt=UselessInt; 
    } 
}; 

class B 
{ 
    A myObject; //<-- here you specify just the type 
    A myObject2; 
    public: 

    B(int AnotherInt) : myObject(AnotherInt/10), myObject2(AnotherInt/2) // <-- after the semicolon you put all the initializations for the data members 
    { 
     // ... do additional initialization stuff here ... 
    } 
}; 

Here你可以找到一個詳細的解釋。

相關問題