如何限制类的实例化只在特定类中进行?
我不想将其限制在单个文件中,因此匿名命名空间不适合我。
请注意,我想让被限制类的声明对整个世界可见,只是全世界只有一个特定的候选者只能实例化它。
我怎样才能做到这一点?
最佳答案
使用 friend
!使类 Foo
成为类 Bar
的友元意味着 Foo
可以访问 Bar
的私有(private)成员。如果您将构造函数设为私有(private),则只有 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
}
关于c++ - 如何确保特定类只能创建另一个类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44246994/