如果我将构造函数声明为私有,可以在另一个类中调用此构造函数 [英] if I declare a constructor as private can i call this constructor in another class
本文介绍了如果我将构造函数声明为私有,可以在另一个类中调用此构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我将构造函数声明为私有,可以在另一个类中调用该构造函数吗?
If I declare a constructor as private can I call this constructor in another class?
class A{
private A(){
...
}
class B {
A a_obj=new A(){} //shows an error--not visible
}
无论如何,我都想声明一个私有构造函数,但是我不能违反它,但是我仍然可以以其他方式使用它吗?
I want to declare a private constructor anyhow, I can''t violate that, but still can I use it in other way around?
推荐答案
使用私有构造函数.
请参阅此 [
You cannot initialize a object using private constructor.
Please see this[^]
不仅您不能实例化具有所有私有构造函数的类(不是从类的外部,而是类可以提供一个创建实例的工厂),但这也是一种众所周知的编程方法.
特别是,这是创建抽象类功能的唯一方法(与较新的OOP语言相比,C ++中没有抽象"关键字).这样的类非常有用,因为一个类层次结构需要一个具有通用功能的通用基类,而该通用基类只能用作基类.用编译器阻止的意外尝试创建此类的实例.
—SA
Not only you cannot instantiate a class with all constructors private (not from outside of the class, but class can provide a factory creating an instance), but this is also a well known method of programming.
In particular, this is the only way to created functionality of abstract classes (there is no "abstract" keyword in C++, in contrast to newer OOP languages). Such classes are very useful it a class hierarchy needs a common base class with common functionality which can only be used as a base class; an accidental attempt to create an instance of such class with be prevented by compiler.
—SA
这篇关于如果我将构造函数声明为私有,可以在另一个类中调用此构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文