我们什么时候需要 C++ 中的私有构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6568486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:22:09  来源:igfitidea点击:

When do we need a private constructor in C++

c++constructorprivate

提问by iammilind

I have a question about private constructor in c++, if the constructor is private, how to create an instance of the class? Should we have a getInstance() method inside the class?

我有一个关于 C++ 中私有构造函数的问题,如果构造函数是私有的,如何创建类的实例?我们应该在类中有一个 getInstance() 方法吗?

回答by iammilind

There are a few scenarios for having privateconstructors:

有几个使用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`
    };
    
  2. Restricting certain type of constructor (i.e. copy constructor, default constructor). e.g. std::fstreamdoesn't allow copying by such inaccessible constructor

  3. 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()) {}
    };
    
  4. For singleton patternswhen the singleton classis not inheritible (if it's inheritible then use a protectedconstructor)

    class A
    {
    public:
       A();
       A(int);
    private:
       A(const A&);  // Neither others nor `friend` can use this
       // A(const A&) = delete;  // C++11 equivalent `private` doesn't matter
    };
    
  1. 限制除friends 之外的所有对象的创建;在这种情况下,所有构造函数都必须是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`
    };
    
  2. 限制特定类型的构造函数(即复制构造函数、默认构造函数)。例如std::fstream不允许通过这种无法访问的构造函数进行复制

  3. 要有一个不应该暴露给外部世界的公共委托构造函数:

    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()) {}
    };
    
  4. 对于class不可继承时的单例模式(如果它是可继承的,则使用protected构造函数)

    class A
    {
    public:
       A();
       A(int);
    private:
       A(const A&);  // Neither others nor `friend` can use this
       // A(const A&) = delete;  // C++11 equivalent `private` doesn't matter
    };
    

Clarification: In case of singletons, a typical way is to have a public: static getInstance()method within the class, which can access the privateconstructor. Eventually it creates and supplies object to the outer world.

说明:在单例的情况下,典型的方法是public: static getInstance()在类中有一个可以访问private构造函数的方法。最终它会创建对象并将其提供给外部世界。

    class Singleton
    {
    public:
       static Singleton& getInstance() {
          Singleton object; // invokes the `private` constructor
          return object;
       }
    private:
       Singleton() {}  // make `protected` for further inheritance
       Singleton(const Singleton&);  // inaccessible
       Singleton& operator=(const Singleton&);  // inaccessible
    };

回答by Matthieu M.

A private constructor is commonly used with Buildermethods, for example in the Named Constructoridiom.

私有构造函数通常与Builder方法一起使用,例如在命名构造函数习语中。

class Point
{
public:
  static Point Polar(double, double);
  static Point Cartesian(double, double);
private:
  Point(double,double);
};

In this (typical) example, the Named Constructor idiom is used to make it explicitly which coordinate system is used to build the Pointobject.

在这个(典型)示例中,命名构造函数习语用于明确说明使用哪个坐标系来构建Point对象。

回答by Tunvir Rahman Tusher

Private Constructor is useful when you want to control the object creation of a class. Lets try in code

当您想要控制类的对象创建时,私有构造函数很有用。让我们试试代码

#include <iostream>
using namespace std;
class aTestClass
{
    aTestClass()//////////private constructor of this class
    {
        cout<<"Object created\n";
    }
    public:

};
int main()
{
    aTestClass a;
    aTestClass *anObject;
}

The line aTestClass acauses an error because this line is indirectly trying to access the private constructor.comment out this line and run the program .it runs absolutely fine.Now question is how to create object in such case. Lets write another program.

aTestClass a行导致错误,因为该行间接尝试访问私有构造函数。注释掉这一行并运行程序。它运行得很好。现在的问题是在这种情况下如何创建对象。让我们编写另一个程序。

#include <iostream>
using namespace std;
class aTestClass
{
    aTestClass()//////////private constructor of this class
    {
        cout<<"Object created\n";
    }
    public:

    aTestClass* getAnObject()/////a public method create an object of this class and return the address of an object of that class
    {

        return (new aTestClass);

    }
};
int main()
{
    //aTestClass a;
    aTestClass *anObject=NULL;
    anObject=anObject->getAnObject();
}

The output is

输出是

Object created

so we have created an object of the class contain a private constructor. Use this concept to implement singleton classThanks

所以我们创建了一个包含私有构造函数的类的对象。 Use this concept to implement singleton class谢谢

回答by murrekatt

Yes, this is commonly used in the Singleton patternwhere the object is accessed through a static member function.

是的,这通常用于通过静态成员函数访问对象的单例模式中。

回答by devil

If some constructor is private, it means that no one but the class itself (and friends) should be able to create instances of it using that constructor. Therefore, you can provide static methods like getInstance() to create instances of the class or create the instances in some friend class/method.

如果某个构造函数是私有的,则意味着除了类本身(和朋友)之外,没有人能够使用该构造函数创建它的实例。因此,您可以提供像 getInstance() 这样的静态方法来创建类的实例或在某些朋友类/方法中创建实例。

回答by Michael Aaron Safyan

It depends on why the constructor was made private in the first place (you should ask whoever wrote the class you are editing). Sometimes a constructor may be made private to disallow copy construction (while allowing construction through some other constructor). Other times a constructor may be made private to disallow creating the class except by the class's "friend"s (this is commonly done if the class is a "helper" that should only be used by the class(es) for which the helper class was created). A constructor may also be made private to force the use of a (usually static) creation function.

这取决于为什么首先将构造函数设为私有(您应该询问编写您正在编辑的类的人)。有时,构造函数可能会被设为私有以禁止复制构造(同时允许通过其他构造函数进行构造)。其他时候,构造函数可能被设为私有以禁止创建类,除非类的“朋友”(如果类是“助手”,则通常会这样做,该类只应由助手类使用的类使用被创建)。也可以将构造函数设为私有以强制使用(通常是静态的)创建函数。

回答by C_Raj

Private constructor in C++ can be use for restricting object creation of constant structure. And you can define similar constant in same scope like enum

C++ 中的私有构造函数可用于限制常量结构的对象创建。您可以在与 enum 相同的范围内定义类似的常量

struct MathConst{
    static const uint8 ANG_180 = 180;
    static const uint8 ANG_90  = 90;

    private:
        MathConst(); // restricting object creation
};

access like MathConst::ANG_180

访问喜欢 MathConst::ANG_180