关于构造函数和析构函数的说明
问题描述:
大家好
有些人可以解释一下构造函数和析构函数的可访问性对作用域的影响以及类的可见性。
关注
Hi All
Can some explain what are the affects of accessibility of constructor and destructor on scope and the visibility of their class.
Regards
答
参见 http://msdn.microsoft.com/en-us/library/4a1hcx0y.aspx [ ^ ]了解有关类的详细信息。
See http://msdn.microsoft.com/en-us/library/4a1hcx0y.aspx[^] for details on classes.
首先,我要说我是从内存写的,所以可能有错误;检查我的陈述。
如果一个类有公共ctor和dtor,那么它可以通过任何代码在任何地方创建(假设纯虚方法没有问题等)。 )。
如果一个类有一个受保护的构造函数,那么只能实例化一个派生类。
如果一个类有一个受保护/私有的析构函数,它可以作为静态对象创建/删除,也可以在堆栈上创建/删除,但不能在堆上创建/删除。或者使用工厂方法。
如果一个类有私有构造函数(没有朋友),可以使用工厂方法创建,但不能使用静态,堆栈或堆创建。
这看起来像是家庭作业;使用一些代码验证上面的语句。我可能错了......
First, let me say that I am writing this from memory, so there may be errors; check my statements.
If a class has public ctor and dtor, then it can be created anywhere by any code (assuming there are no issues with pure virtual methods etc.).
If a class has a protected constructor, then only a derived class can be instantiated.
If a class has a protected/private destructor, it can be created/deleted as a static object, or on the stack but not on the heap. Or using a factory method.
If a class has a private constructor (and no friends) it can be created using a factory method but not static, stack or heap.
This looks like homework; validate my statements above with some code. I might be wrong...