如何存储单例类的引用? [英] How to store a reference of a singleton class?
问题描述
我正在开发一个关于经销商向玩家交易卡的项目。
我有单身课经销商
和另一个名为 Player
。
I am working on a project relating to a dealer dealing cards to players.
I have the singleton class Dealer
and another class called Player
.
我已为经销商做了
instance >这部分是我困惑的:
I have made the instance()
method for Dealer
and this part is where I am confused:
对于单例 Player
类,如何创建一个私有成员名为代理商
,其中包含对单身经销商
实例的引用?
For the singleton Player
class, how do I create a private member called dealer
that holds a reference to the singleton Dealer
instance?
推荐答案
首先,你应该问自己,如果你真的需要一个单例类来解决这个问题。
In the first place you should ask yourself, if you really need a singleton class to solve this problem at all.
您可以随时将对经销商
的实例的引用传递给您的玩家
class:
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;
};
无论如何,它都是在堆栈,堆上或单例实例上构建的。 p>
no matter, wether it was constructed on the stack, on the heap or as singleton instance.
对于单例
Player
如何创建私人成员..._
For the singleton
Player
class, how do I create a private member ..._
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;
};
这篇关于如何存储单例类的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!