开发者

Is it possible to have an instance of a class as a data member of another class?

I have a Board class where the constructor takes in the dimensions of the board as the parameter. I also have a Puzzle class that holds pieces and I want it to have a Board as a data member. I want it like this so that when I create an instance of P开发者_如何学JAVAuzzle, I will have my instance of Board created as well so I don't have to make separate instances as a user. However, when I declare the board in my Puzzle.h file, it needs an actual number for the Board constructor:

// Puzzle.h file

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

Is there a way to have an object of a class be a data member for another class if that object hasn't been created yet?


If I understand correctly, the problem is that you need to instantiate your board correctly:

 class Puzzle {
 public:
       Board theBoard;

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


You have to declare the data member without specifying anything more than the type, and then initialize it with the special constructor initialization list syntax. An example will be much clearer:

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 you can find a detailed explanation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜