When do we need a private constructor in C++?(我们什么时候需要 C++ 中的私有构造函数?)
问题描述
我有一个关于 C++ 中私有构造函数的问题.如果构造函数是私有的,我如何创建类的实例?
I have a question about private constructors in C++. If the constructor is private, how can I create an instance of the class?
我们应该在类内部有一个 getInstance() 方法吗?
Should we have a getInstance() method inside the class?
推荐答案
private
构造函数有几种情况:
There are a few scenarios for having private
constructors:
限制除
friend
以外的所有对象的创建;在这种情况下,所有构造函数都必须是private
Restricting object creation for all but
friend
s; in this case all constructors have to beprivate
class A
{
private:
A () {}
public:
// other accessible methods
friend class B;
};
class B
{
public:
A* Create_A () { return new A; } // creation rights only with `B`
};
限制特定类型的构造函数(即复制构造函数、默认构造函数).例如std::fstream
不允许通过这种不可访问的构造函数进行复制
Restricting certain type of constructor (i.e. copy constructor, default constructor). e.g. std::fstream
doesn't allow copying by such inaccessible constructor
class A
{
public:
A();
A(int);
private:
A(const A&); // C++03: Even `friend`s can't use this
A(const A&) = delete; // C++11: making `private` doesn't matter
};
要有一个公用的委托构造函数,不应该暴露给外部世界:
To have a common delegate constructor, which is not supposed to be exposed to the outer world:
class A
{
private:
int x_;
A (const int x) : x_(x) {} // common delegate; but within limits of `A`
public:
A (const B& b) : A(b.x_) {}
A (const C& c) : A(c.foo()) {}
};
对于 单例模式,当单例 class
不可继承时(如果是可继承然后使用 protected
构造函数)
For singleton patterns when the singleton class
is not inheritible (if it's inheritible then use a protected
constructor)
class Singleton
{
public:
static Singleton& getInstance() {
Singleton object; // lazy initialization or use `new` & null-check
return object;
}
private:
Singleton() {} // make `protected` for further inheritance
Singleton(const Singleton&); // inaccessible
Singleton& operator=(const Singleton&); // inaccessible
};
这篇关于我们什么时候需要 C++ 中的私有构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我们什么时候需要 C++ 中的私有构造函数?


- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01