C++ 中的构造函数可以是私有的吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18132590/
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
Can a Constructor be Private in C++?
提问by Abhishek Jain
Can a constructor be private in C++? If yes then how can we call it?
C++ 中的构造函数可以是私有的吗?如果是,那么我们怎么称呼它?
class Puma
{
int a = 10;
Puma()
{
cout << a;
}
};
int main()
{
Puma pum;
return o;
}
Can this program run? If not then how can we call Puma()
constructor as it is private?
这个程序可以运行吗?如果不是,那么我们如何调用Puma()
构造函数,因为它是私有的?
回答by Benjamin Lindley
Yes, a constructor can be private. And you can call it with member functions (static or non) or friend functions.
是的,构造函数可以是私有的。您可以使用成员函数(静态或非)或友元函数调用它。
class Puma
{
public:
static Puma create(int a) { return Puma(a); }
private:
int age;
Puma(int a) :age(a) {}
friend Puma createPuma(int a);
};
Puma createPuma(int a) { return Puma(a); }
For possible use cases, see the Factory Pattern, or the Named Constructor Idiom.
有关可能的用例,请参阅Factory Pattern或Named Constructor Idiom。
回答by RiaD
Yes. Constructor may be private.
是的。构造函数可能是私有的。
In this case you may create class
在这种情况下,您可以创建类
- Using another (public) constructor
- Calling constructor from the same class
- Calling constructor from the friend class/function
- 使用另一个(公共)构造函数
- 从同一个类调用构造函数
- 从朋友类/函数调用构造函数
回答by taocp
In your code, the program cannot run since you have defined a constructor and it is private. Therefore, in your current code, there is no way to create objects of the class, making the class useless in a sense.
在您的代码中,程序无法运行,因为您已经定义了一个构造函数并且它是私有的。因此,在您当前的代码中,无法创建该类的对象,从而使该类在某种意义上毫无用处。
One way to do is that you can provide public static functions, those static functions call the private constructors to create objects of class.
一种方法是您可以提供公共静态函数,这些静态函数调用私有构造函数来创建类对象。
One minor thing:
一件小事:
return o;
should be
应该
return 0;
回答by alex
Singleton can have a private constructor that will be called from a static method of a class.
Singleton 可以有一个私有构造函数,该构造函数将从类的静态方法中调用。
回答by Basile Starynkevitch
Yes a constructor can be private. It is useful when called by a static member function (or a friend), e.g.
是的,构造函数可以是私有的。当被静态成员函数(或朋友)调用时很有用,例如
class Even {
private:
int x;
Even(int a) : x(a) {};
public:
int get () const { return 2*x; };
static EVen* make(int y) { return new Even(y); };
};
the example is not very realistic, but you get the idea. In the using code, do
这个例子不太现实,但你明白了。在使用代码中,做
Even* e = Even::make(3);