什么时候需要C ++中的私有构造函数? [英] When do we need a private constructor in C++?

查看:56
本文介绍了什么时候需要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:

  1. 限制除 friend 以外的所有对象的对象创建;在这种情况下,所有构造函数都必须是 private

  1. Restricting object creation for all but friends; in this case all constructors have to be private

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 是不可继承的(如果它是可继承的,然后使用受保护的构造函数)

  • 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 ++中的私有构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆