开发者

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

开发者 https://www.devze.com 2022-12-21 06:13 出处:网络
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 l

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

精彩评论

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

关注公众号