如果构造函数位于私有部分,为什么我们不能创建对象?

发布于 2024-08-29 11:04:27 字数 708 浏览 1 评论 0原文

我想知道如果构造函数位于私有部分,为什么我们不能创建对象。我知道,如果我将一个方法设为静态,我可以使用以下方法调用该方法

<classname> :: <methodname(...)>;

,但我不明白为什么我们不能创建对象。

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

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();
}

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

I want to know why cant we create object if the constructor is in private section. I know that if i make a method static i can call that method using

<classname> :: <methodname(...)>;

But why can't we create object is what I don't understand.

I also know if my method is not static then also I can call function by the following:

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();
}

So, my question is: why can't we create an object when constructor is private?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

落日海湾 2024-09-05 11:04:27

因为程序无法访问它,所以这就是私有的意思。如果您将成员函数或变量声明为私有,您也将无法访问它们。创建私有构造函数实际上是 C++ 中的一项有用技术,因为它允许您说只有特定的类才能创建该类型的实例。例如:

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

class B {
   public:
     A * MakeA() {
        return new A;
     }
};

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

Because it is not accessible to the program, that's what private means. If you declared a member function or variable private, you would not be able to access them either. Creating private constructors is actually a useful technique in C++, as it allows you to say that only specific classes can create instances of the type. For example:

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

class B {
   public:
     A * MakeA() {
        return new A;
     }
};

Only B can create A objects - this is useful when implementing the factory pattern.

蝶…霜飞 2024-09-05 11:04:27

构造函数是一种特殊的成员函数。在访问它时,它遵循与任何其他方法相同的规则。私有访问标签可防止类用户调用/访问在其下声明的成员。

A constructor is a special member function. It obeys the same rules as any other method when it comes to accessing it. The private access label prevents class users from invoking/accessing members declared under it.

季末如歌 2024-09-05 11:04:27

“new”运算符需要调用构造函数,因此如果构造函数是私有的,则除了在类 A 本身的成员函数内之外,您无法执行代码“obj = new A”。

我猜你遇到的是一种在 Java 中经常使用的技术(是的,我知道你正在编写 C++,但原理是相同的),类的设计者希望确保唯一一个该类的一个实例将永远存在(称为“单例”)。为了实现这一点,他需要防止其他代码使用 new 创建该类的更多实例,而将构造函数设置为私有是实现此目的的一种方法。下面是一段说明该技术的 Java 代码。

public class MySingleton {

  private MySingleton() {
      // Private constructor, to prevent instantiation using "new"
      // outside of this class.
  }

  public synchronized static MySingleton getInstance() {
    static MySingleton instance = null;

    if (instance == null) {
        // I can use new here because I'm inside the class.
        instance = new MySingleton();
    }
    return instance;
  }

}

即使您不懂 Java,其语法与 C++ 非常相似,您也应该了解这段代码的作用。要点是,在代码中的其他位置获取对 MySingleton 类实例的引用的唯一方法是调用静态类成员 getInstance()。

  MySingleton obj = MySingleton.getInstance();

The "new" operator needs to call the constructor, so if the constructor is private you can not execute the code "obj = new A" except inside member functions of the class A itself.

I would guess that what you have encountered is a technique that is very often used in Java (and yes I know you're writing C++, but the principle is the same) where the designer of the class wants to make sure that one and only one instance of this class will ever exist (which is called a "singleton"). To achieve this, he needs to prevent other code from creating further instances of the class using new, and making the constructor private is one way to do that. Here's a piece of Java code illustrating the technique.

public class MySingleton {

  private MySingleton() {
      // Private constructor, to prevent instantiation using "new"
      // outside of this class.
  }

  public synchronized static MySingleton getInstance() {
    static MySingleton instance = null;

    if (instance == null) {
        // I can use new here because I'm inside the class.
        instance = new MySingleton();
    }
    return instance;
  }

}

Even if you don't know Java, the syntax is similar enough to C++ that you should understand what this code is doing. The point is that the only way to get a reference to an instance of the MySingleton class elsewhere in the code is to call the static class member getInstance().

  MySingleton obj = MySingleton.getInstance();
祁梦 2024-09-05 11:04:27

您无法实例化您的类,因为构造函数是私有private 成员变量和函数不能在类本身之外使用。

如果您希望能够实例化您的类,您有两种选择。

选项1是创建构造函数。在绝大多数情况下,这是正确的做法。将构造函数设置为私有是一种有用的技术,但仅限于尝试实现特定目标时。

选项 2 是创建一个 public static 工厂方法。当选项 1 不可行时,您通常会这样做。

class A
{
     A();
     public:
    static A* Create() { return new A; }
        void fun1();
        void fun2();
        void fun3();
};


int main()
{
     A *obj = A::Create();
     //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();
}

You can't instantiate your class because the constructor is private. private member variables and functions cannot be used outside of the class itself.

If you want to be able to instantiate your class, you have two options.

Option 1 is to make the constructor. This is the Right Thing to do in the vast majority of cases. Making a constructor private is a useful technique, but only when trying to accomplish specific goals.

Option 2 is to create a public static factory method. You would typically do this when Option 1 isn't an option.

class A
{
     A();
     public:
    static A* Create() { return new A; }
        void fun1();
        void fun2();
        void fun3();
};


int main()
{
     A *obj = A::Create();
     //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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文