C++ - 如何在另一个类中使用构造函数private实例化对象

waa*_*919 0 c++ object instantiation

我有一个class Piece我已经放置了默认构造函数private,因为我想在创建对象时只使用特定的构造函数:

class Piece
{
private:
  Piece();
public:
  Piece (int var1, int var2);
  ~Piece();
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个class Gamevector of Pieces:

class Game
{
private:
  std::vector<Piece> m_pieces;
public:
  Game();
  ~Game();
  CreatePieces(); //<-- only here, I will create the Piece objects, not in the constructor
}
Run Code Online (Sandbox Code Playgroud)

现在我想要一个class Foo,其中包含Piece:

class Foo
{
private:
  Piece m_piece;//ERROR!!! cannot access private member declared in class 'Piece'
public:
  Foo();
  ~Foo();
}
Run Code Online (Sandbox Code Playgroud)

我的问题:

现在我需要使用默认的构造函数m_pieceFoo class.但我想避免这种情况,并按照我在使用时的方式使用Game class.

无论如何,我可以保持我的Piece class 原样,并创建一个Piece object,就像在Foo class,但Piece (int var1, int var2);在我的Foo()构造函数的构造函数初始化它?

Jon*_*ter 7

您可以m_pieceFoo构造函数中初始化以调用特定的构造函数,例如:

class Foo
{
    Foo() : m_piece(0,0)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)