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
friends; 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++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				