私有构造函数 [英] private constructor

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

问题描述


可能重复:

我们在哪里需要私有构造函数?我们如何实例化具有私有构造函数的类?

Where do we need private constructor? How can we instantiate a class having private constructor?

推荐答案

私有构造函数意味着用户不能直接实例化类。相反,您可以使用类似于命名构造函数成语创建对象,其中包含 static 类函数,可以创建和返回类的实例。

Private constructor means a user can not directly instantiate a class. Instead, you can create objects using something like the Named Constructor Idiom, where you have static class functions that can create and return instances of a class.

命名构造函数习语更直观地使用类。在C ++常见问题提供的示例是一个类,可以用来表示多个坐标系。

The Named Constructor Idiom is for more intuitive usage of a class. The example provided at the C++ FAQ is for a class that can be used to represent multiple coordinate systems.

这是直接从链接拉。它是一个表示不同坐标系中的点的类,但它可以用于表示矩形和极坐标点,因此为了使用户更直观,使用不同的函数来表示返回的 Point 代表。

This is pulled directly from the link. It is a class representing points in different coordinate systems, but it can used to represent both Rectangular and Polar coordinate points, so to make it more intuitive for the user, different functions are used to represent what coordinate system the returned Point represents.

 #include <cmath>               // To get std::sin() and std::cos()

 class Point {
 public:
   static Point rectangular(float x, float y);      // Rectangular coord's
   static Point polar(float radius, float angle);   // Polar coordinates
   // These static methods are the so-called "named constructors"
   ...
 private:
   Point(float x, float y);     // Rectangular coordinates
   float x_, y_;
 };

 inline Point::Point(float x, float y)
   : x_(x), y_(y) { }

 inline Point Point::rectangular(float x, float y)
 { return Point(x, y); }

 inline Point Point::polar(float radius, float angle)
 { return Point(radius*std::cos(angle), radius*std::sin(angle)); }

还有很多其他的回应也符合为什么私人构造函数被使用的精神

There have been a lot of other responses that also fit the spirit of why private constructors are ever used in C++ (Singleton pattern among them).

另一件你可以做的事情是阻止类的继承,因为派生类将无法访问您的类的构造函数。当然,在这种情况下,你仍然需要一个函数来创建类的实例。

Another thing you can do with it is to prevent inheritance of your class, since derived classes won't be able to access your class' constructor. Of course, in this situation you still need a function that creates instances of the class.

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

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