我知道如何防止在C++中动态实例化类.(定义我自己的'new'运算符)但是有一种简单的方法来阻止静态实例化以便强制动态实例吗?也就是说,我该怎么做...(这不是一个可派生的抽象基类.只是一个简单的类)
class B {
};
B b; // how do I prevent this without using friends or some derived class trick
B* b;
b = new B; // still want to be able to do this.
Run Code Online (Sandbox Code Playgroud)
Dra*_*sha 13
您可以通过将c'tor设为私有来阻止它:
class B {
B() {}
public:
static B* alloc() { return new B; }
};
Run Code Online (Sandbox Code Playgroud)
而不是b = new B;你会做:b = B::alloc();