私人建设者

时间:2011-01-10 15:50:00

标签: c++ private-constructor

  

可能重复:
  What is the use of making constructor private in a class?

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

7 个答案:

答案 0 :(得分:64)

私有构造函数意味着用户无法直接实例化类。相反,您可以使用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 ++中使用的精神(其中包括Singleton模式)。

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

答案 1 :(得分:29)

一种常见的用法是在单例模式中,您只需要存在一个类的实例。在这种情况下,您可以提供一个static方法来执行对象的实例化。这样就可以控制实例化特定类的对象数量。

答案 2 :(得分:6)

当您不希望用户实例化您的类时,

私有构造函数很有用。要实例化这样的类,需要声明一个静态方法,它执行'new'并返回 指针。

有私人ctors的课程不能放入STL容器,因为他们需要复制ctor。

答案 3 :(得分:5)

如果有其他方法可以生成实例,那么构造函数是私有的是合理的。显而易见的例子是模式Singleton(每个调用返回相同的实例)和Factory(每次调用通常创建新实例)。

答案 4 :(得分:2)

当你想要实现单身时,这很常见。该类可以有一个静态的“工厂方法”,用于检查该类是否已经实例化,如果没有,则调用构造函数。

答案 5 :(得分:1)

例如,您可以在友元类或朋友函数中调用私有构造函数。

Singleton pattern通常使用它来确保没有人创建更多预期类型的​​实例。

答案 6 :(得分:1)

一个常见用途是模板类型的解决方法类,如下所示:

template <class TObj>
class MyLibrariesSmartPointer
{
  MyLibrariesSmartPointer();
  public:
    typedef smart_ptr<TObj> type;
};

显然,公共的非实现构造函数也可以工作,但是如果有人试图实例化MyLibrariesSmartPointer<SomeType>而不是MyLibrariesSmartPointer<SomeType>::type,那么私有构造者会引发编译时错误而不是链接时错误。 desireable。

相关问题