In the first place you should ask yourself, if you really need a singleton class to solve this problem at all.
You can always pass the reference to an instance of Dealer
to the constructor of your Player
class:
class Player {
public:
Player(Dealer& dealer_) : dealer(dealer_) {}
private:
Dealer& dealer;
};
no matter, wether it was constructed on the stack, on the heap or as singleton instance.
For the singleton Player
class, how do I create a private member ..._
The commonly recommended c++ singleton implementation pattern is
class Dealer{
public:
static Dealer& instance() {
static Dealer theDealer;
return theDealer;
}
void foo() {}
private:
Dealer() {}
Dealer(const Dealer&) = delete;
Dealer& operator=(const Dealer&) = delete;
};
NOTE: You don't necessarily need to store a reference to Dealer
class in your client class, but you can simply access the singleton instance and call the desired non static member function
Dealer::instance.foo();
If you insist to create a reference member to the singleton though, you can do:
class Player {
public:
Player() : dealer(Dealer::instance()) {}
private:
Dealer& dealer;
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…