Possible Duplicate:
What is the use of making constructor private in a class?
我们在哪里需要私有(private)构造函数?我们如何实例化具有私有(private)构造函数的类?
最佳答案
私有(private)构造器意味着用户不能直接实例化一个类。相反,您可以使用 Named Constructor Idiom 之类的东西创建对象。 ,其中有 static
类函数,可以创建和返回类的实例。
Named Constructor Idiom 用于更直观地使用类。 C++ FAQ 中提供的示例是针对可用于表示多个坐标系的类。
这是直接从链接中提取的。它是一个表示不同坐标系的点的类,但它既可以表示直角坐标点,也可以表示极坐标点,所以为了让用户更直观,使用不同的函数来表示返回的Point 代表。
#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)); }
还有很多其他的回应也符合 C++ 中为何使用私有(private)构造函数的精神(其中包括单例模式)。
你可以用它做的另一件事是prevent inheritance of your class ,因为派生类将无法访问您的类的构造函数。当然,在这种情况下,您仍然需要一个创建类实例的函数。
https://stackoverflow.com/questions/4648602/