c++ - 私有(private)构造函数

这个问题在这里已经有了答案:
关闭11年前.

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/

相关文章:

c++ - std::vector 与 std::list 与 std::slist 的相对性能?

c++ - 多行 DEFINE 指令?

c++ - 为什么 C/C+ +'s "#pragma once"不是 ISO 标准?

c++ - 为什么优化会杀死这个功能?

c++ - 在 std::map 中更改元素键的最快方法是什么

c++ - 使用 C++ 基类构造函数?

c++ - 从构造函数的初始化列表中捕获异常

c++ - queue::push 后双重释放或损坏

c++ - std::tuple get() 成员函数

c++ - 三向比较运算符与减法有何不同?