【发布时间】:2011-02-11 00:04:54
【问题描述】:
我想知道如果构造函数在私有部分中,为什么我们不能创建对象。我知道如果我将方法设为静态,我可以使用
调用该方法<classname> :: <methodname(...)>;
但为什么我们不能创建对象是我不明白的。
我也知道如果我的方法不是静态的,那么我也可以通过以下方式调用函数:
class A
{
A();
public:
void fun1();
void fun2();
void fun3();
};
int main()
{
A *obj =(A*)malloc(sizeof(A));
//Here we can't use new A() because constructor is in private
//but we can use malloc with it, but it will not call the constructor
//and hence it is harmful because object may not be in usable state.
obj->fun1();
obj->fun2();
obj->fun3();
}
所以,我的问题是:为什么我们不能在构造函数是私有的时候创建一个对象?
【问题讨论】:
-
这不是有史以来最伟大的问题,但我认为它不值得被否决。
标签: c++ object constructor private