![](/img/trans.png)
[英]How to instantiate an object to another class in the constructor of a class? C++
[英]C++ - How to instantiate object with constructor private in another class
我有一個class Piece
,我把默認的構造函數設置為private
,因為在創建對象時我只想使用特定的構造函數:
class Piece
{
private:
Piece();
public:
Piece (int var1, int var2);
~Piece();
}
現在我有一個class Game
其中有一個vector 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
}
現在,我要創建一個class Foo
,其中包含一個Piece
:
class Foo
{
private:
Piece m_piece;//ERROR!!! cannot access private member declared in class 'Piece'
public:
Foo();
~Foo();
}
我的問題:
現在,我需要對Foo class
的m_piece
使用默認的構造函數。 但是我想避免這種情況,並像在Game class
那樣使用它。
反正是有,我可以讓我的Piece class
,因為它是 ,並創建一個Piece object
,就像在Foo class
,但與構造函數初始化Piece (int var1, int var2);
在我的Foo()
構造函數上?
您可以在Foo
構造函數中初始化m_piece
來調用特定的構造函數,例如:
class Foo
{
Foo() : m_piece(0,0)
{
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.