2017-05-29 24 views
8

如何限制仅在特定类中的类的实例化?如何确保一个特定的类只能创建另一个类的实例?

我不想限制它在一个文件中,所以匿名命名空间不适合我。

请注意,我想让限制类的声明对整个世界都是可见的,只是全世界只有一个特定的候选者只能实例化它。

我该如何做到这一点?

+4

将该孤立类作为“朋友”与非公共构造类的“私人”构造函数结合使用应该有效。 –

+0

“我想让被限制类的声明对整个世界都是可见的,只有一个来自整个世界的特定候选人只能实例化并访问它”然后,为什么要显示它,如果你不能碰它?我错过了什么吗? – ZDF

+0

你想要一个Singleton模式吗?实例化它一次,并使用一个实例的一切? – dage5

回答

5

你可以采用passkey pattern(从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_tallowed_t的朋友,避免了复杂的代理模式。

+0

这是一个不错的解决方案。非常感谢 :)。 – Mariners

+0

@Mariners不客气。也请看[Matthieu的描述](https:// stackoverflow。com/a/3218920/3235496)的实施细节模式。 – manlio

11

使用friend s!制作班级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 
} 
相关问题