[英]How to ensure a specific class only can create an instance of another class?
如何僅在特定類中限制類的實例化?
我不想在單個文件中限制它,因此匿名命名空間不適合我。
請注意,我想讓整個世界都可以看到要限制的類的聲明,只是來自整個世界的一個特定候選者只能實例化它。
我怎樣才能做到這一點?
用friend
的! 使類Foo
成為類Bar
的朋友意味着Foo
可以訪問Bar
的私有成員。 如果您將構造函數設為私有,則只有Foo
才能創建Bar
實例。
struct restricted_t {
friend struct allowed_t; // allow 'allowed_t' to access my private members
private:
// nobody can construct me (except for my friends of course)
restricted_t() = default;
};
struct allowed_t {
restricted_t yes; // ok
};
struct not_allowed_t {
restricted_t no; // not ok
};
int main() {
allowed_t a; // ok, can access constructor
not_allowed_t b; // error, constructor is private
}
你可以采用密鑰模式 (借用Rakete1111的例子):
class pass_key { friend class allowed_t; pass_key() {} };
struct restricted_t
{
restricted_t(pass_key);
};
class allowed_t
{
public:
allowed_t() : yes(pass_key()) {} // ok, allowed_t is a friend of pass_key
private:
restricted_t yes;
};
class not_allowed_t
{
public:
not_allowed_t() : no(pass_key()) {} // not ok, pass_key() is private
private:
restricted_t no;
};
int main()
{
allowed_t a; // OK, can access constructor
not_allowed_t b; // ERROR, only a friend of the key
// class has access to the restricted
// constructor
}
該模式允許更精細的訪問控制,而不是使restricted_t
成為allowed_t
的朋友,並避免復雜的代理模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.