c++ - 如何确保特定类只能创建另一个类的实例?

标签 c++ c++11

如何限制类的实例化只在特定类中进行?

我不想将其限制在单个文件中,因此匿名命名空间不适合我。

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

我怎样才能做到这一点?

最佳答案

使用 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/

相关文章:

c++ - 如何在C++上启动异步线程

c++ - 根据键的类型选择 map 或 unordered_map

c++ - GLSL C++ glVertexAttribPointer & glDrawElements 返回 GL_INVALID_OPERATION

c++ - 生成 makefile 时不包含 cmake c++11 标志

c++ - 这是优化器的怪癖还是语言规则禁止优化的结果?

c++ - 使用 std::min "no matching function for call to ‘min(<brace-enclosed initializer list>)’ 时出错“

c++ - 在 C++ 中显示所有基本类型的数据大小的程序

C++ map.erase() 导致不必要的平衡

c++ - 运行时类型推导和代码重复

c++ - Boost Graph Library 中的顶点描述符和索引有什么区别?