任何人都可以告诉如何创建类,以便它不能被任何其他类继承.
class A {
public :
int a;
int b;
};
class B : class A {
public :
int c;
};
Run Code Online (Sandbox Code Playgroud)
在上面的程序中,我不想允许其他类被B类继承
Jar*_*d42 13
标记该类final(从C++ 11开始):
class A final {
public :
int a;
int b;
};
Run Code Online (Sandbox Code Playgroud)
如果您使用的是C++ 11或更高版本,则可以使用该final关键字,就像提到的其他答案一样.这应该是推荐的解决方案.
但是,如果必须使用C++ 03/C++ 98,您可以创建类的构造函数private,并使用工厂方法或类创建此类的对象.
class A {
private:
A(int i, int j) : a(i), b(j) {}
// other constructors.
friend A* create_A(int i, int j);
// maybe other factory methods.
};
A* create_A(int i, int j) {
return new A(i, j);
}
// maybe other factory methods.
Run Code Online (Sandbox Code Playgroud)