私有部分的构造函数 [英] Constructor in private section

查看:80
本文介绍了私有部分的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



是否可以在私有范围内声明类的构造函数?



如果是这样,你能举一个小例子吗?



提前致谢。





问候,

Joy

Hello Everyone,

Is it possible to declare constructor of a class in private scope?

If so, can you please give one small example?

Thanks in advance.


Regards,
Joy

推荐答案

,有可能的。例如,它以Singleton模式使用,请参阅此 Stack Overflow问题 [ ^ ]示例代码。
Yes, it is possible. It is used, for instance, in the Singleton pattern, see this Stack Overflow question [^] for sample code.


是的,可以将构造函数声明为 private



当您将构造函数声明为私有时,您无法直接从外部实例化该类。只有在类的内部,您才能创建自己的对象。你使用 static 函数。



一些例子:



1。在创建单例类时(程序中只存在一个类的对象)。

Yes it is possible to declare constructors as private.

When you declare the constructor as private, you cannot directly instantiate the class from outside. And from only the inside of the class you can create an object of itself. You use static functions for this.

Some examples:

1. When you're creating singleton classes (Where only one object of your class exists in your program).
class Foo
{
private:
   Foo(){}

public:
   static Foo& get_instance()
   {
      static Foo global_instance;
      return global_instance;
   }
};



像这样创建上述类的 实例:


Create the instance of the above class like this:

Foo& ins = Foo::get_instance();





2。使用静态方法创建类的实例。



2. Using static methods to create an instance of a class.

class Foo
{
private:
   Foo(){}
public:
   static Foo* create_instance()
   {
      return new Foo();
   }
};



像这样创建这个类的实例:


Create instances of this class like this:

Foo * ins_a = Foo::create_instance();
Foo * ins_b = Foo::create_instance();


是的,你可以:它经常用在Singleton模式中给这个类并且只有类控制何时可以实例化类实例。

Yes, you can: it is often used in the Singleton Pattern to give the class and only the class control over when a class instance can be instantiated.
class MyClass
{
private:
  MyClass();
};

Google或Wiki可以帮助您提供更完整的示例 - 查找Singleton Pattern C ++并找到大量示例。

Google or Wiki can help you will more complete examples - look for "Singleton Pattern C++" and you will find plenty of examples.


这篇关于私有部分的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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