C++ 私有构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4648602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
private constructor
提问by Atul
Possible Duplicate:
What is the use of making constructor private in a class?
可能的重复:
在类中将构造函数设为私有有什么用?
Where do we need private constructor? How can we instantiate a class having private constructor?
我们在哪里需要私有构造函数?我们如何实例化具有私有构造函数的类?
回答by wkl
Private constructor means a user cannot 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.
私有构造函数意味着用户不能直接实例化一个类。相反,您可以使用命名构造函数惯用语之类的东西来创建对象,其中您拥有static
可以创建和返回类实例的类函数。
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.
命名构造函数习语是为了更直观地使用类。C++ FAQ 中提供的示例适用于可用于表示多个坐标系的类。
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.
这是直接从链接中拉出来的。它是一个表示不同坐标系下的点的类,但它既可以表示矩形坐标点,也可以表示极坐标点,因此为了让用户更直观,使用不同的函数来表示返回的坐标系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)); }
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).
还有很多其他的回应也符合为什么在 C++ 中使用私有构造函数的精神(其中包括单例模式)。
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.
您可以用它做的另一件事是防止继承您的类,因为派生类将无法访问您的类的构造函数。当然,在这种情况下,您仍然需要一个创建类实例的函数。
回答by Naveen
One common use is in the singleton pattern where you want only one instance of the class to exist. In that case, you can provide a static
method which does the instantiation of the object. This way the number of objects instantiated of a particular class can be controlled.
一种常见用途是在单例模式中,您只希望该类存在一个实例。在这种情况下,您可以提供一个static
方法来实例化对象。通过这种方式,可以控制特定类实例化的对象数量。
回答by vrdhn
private constructor are useful when you don't want your class to be instantiated by user. To instantiate such classes, you need to declare a static method, which does the 'new' and returns the pointer.
当您不希望您的类被用户实例化时,私有构造函数很有用。要实例化此类类,您需要声明一个静态方法,该方法执行“new”并返回指针。
A class with private ctors can not be put in the STL containers, as they require a copy ctor.
不能将具有私有构造函数的类放入 STL 容器中,因为它们需要复制构造函数。
回答by Andrey
It is reasonable to make constructor private if there are other methods that can produce instances. Obvious examples are patterns Singleton (every call return the same instance) and Factory (every call usuallycreate new instance).
如果有其他方法可以生成实例,则将构造函数设为私有是合理的。明显的例子是单例模式(每次调用都返回相同的实例)和工厂模式(每次调用通常都会创建新实例)。
回答by unwind
It's common when you want to implement a singleton. The class can have a static "factory method" that checks if the class has already been instantiated, and calls the constructor if it hasn't.
当您想要实现单例时,这很常见。类可以有一个静态的“工厂方法”,用于检查类是否已经被实例化,如果没有,则调用构造函数。
回答by Simone
For example, you can invoke a private constructor inside a friend class or a friend function.
例如,您可以在友元类或友元函数中调用私有构造函数。
Singleton patternusually uses it to make sure that nobody creates more instances of the intended type.
单例模式通常使用它来确保没有人创建更多预期类型的实例。
回答by smerlin
One common use is for template-typedef workaround classes like following:
一种常见用途是模板 typedef 解决方法类,如下所示:
template <class TObj>
class MyLibrariesSmartPointer
{
MyLibrariesSmartPointer();
public:
typedef smart_ptr<TObj> type;
};
Obviously a public non-implemented constructor would work aswell, but a private construtor raises a compile time error instead of a link time error, if anyone tries to instatiate MyLibrariesSmartPointer<SomeType>
instead of MyLibrariesSmartPointer<SomeType>::type
, which is desireable.
显然,公共未实现的构造函数也可以工作,但私有构造函数会引发编译时错误而不是链接时错误,如果有人试图 instatiateMyLibrariesSmartPointer<SomeType>
而不是MyLibrariesSmartPointer<SomeType>::type
,这是可取的。