如果构造函数在私有部分,为什么我们不能创建Object?

Abh*_*eet 2 c++ constructor private object

我想知道为什么我们不能创建对象,如果构造函数在私有部分.我知道如果我使方法静态,我可以调用该方法

<classname> :: <methodname(...)>;
Run Code Online (Sandbox Code Playgroud)

但为什么我们不能创造对象是我不明白的.

我也知道如果我的方法不是静态的,那么我也可以通过以下方式调用函数:

class A
{
     A();
     public:
        void fun1();
        void fun2();
        void fun3();
};


int main()
{
     A *obj =(A*)malloc(sizeof(A));
     //Here we can't use new A() because constructor is in private 
     //but we can use malloc with it, but it will not call the constructor
     //and hence it is harmful because object may not be in usable state.
     obj->fun1();
     obj->fun2();
     obj->fun3();
}
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是:为什么我们不能在构造函数是私有时创建一个对象?

小智 9

因为程序无法访问它,所以私有意味着什么.如果您声明了成员函数或变量private,那么您也无法访问它们.在C++中创建私有构造函数实际上是一种有用的技术,因为它允许您说只有特定的类才能创建该类型的实例.例如:

class A {
   A() {} // private ctor
   friend class B;
};

class B {
   public:
     A * MakeA() {
        return new A;
     }
};
Run Code Online (Sandbox Code Playgroud)

只有B可以创建A对象 - 这在实现工厂模式时很有用.