在C ++中防止类继承 [英] Prevent class inheritance in C++
问题描述
我最近的一个朋友问我如何在C ++中防止类继承。他希望编辑失败。
我在想,并找到3个答案。
pre>
class CBase
{
public:
static CBase * CreateInstance()
{
CBase * b1 = new CBase();
return b1;
}
private:
CBase(){}
CBase(CBase3){}
CBase& operator =(CBase&){}
};
2)使用CSealed base class,private ctor&虚拟继承
class CSealed
{
private:
CSealed(){
}
朋友类CBase;
};
class CBase:virtual CSealed
{
public:
CBase(){
}
};
3)使用CSealed基类,protected ctor&虚拟继承
class CSealed
{
protected:
CSealed(){
}
};
class CBase:virtual CSealed
{
public:
CBase(){
}
};
所有上述方法确保CBase类不能继承。
我的问题是:
1)哪个是最好的方法?还有其他方法吗?
2)方法2& 3将不工作,除非CSealed类继承为virutally。这是为什么 ?它与vdisp ptr有什么关系?
PS:
上面的程序是在MS C ++编译器(Visual Studio)。
reference: http://www.codeguru.com/forum/archive/ index.php / t-321146.html
从C ++ 11开始,例如
class CBase final
{
...
我可以看到的主要原因是想做这件事(我找到这个问题的原因)类作为非子类,因此您可以安全地使用非虚拟析构函数,并完全避免vtable。
Recently one of my friend asked me how to prevent class inheritance in C++. He wanted the compilation to fail.
I was thinking about it and found 3 answers. Not sure which is the best one.
1) Private Constructor(s)
class CBase
{
public:
static CBase* CreateInstance()
{
CBase* b1 = new CBase();
return b1;
}
private:
CBase() { }
CBase(CBase3) { }
CBase& operator=(CBase&) { }
};
2) Using CSealed base class, private ctor & virtual inheritance
class CSealed
{
private:
CSealed() {
}
friend class CBase;
};
class CBase : virtual CSealed
{
public:
CBase() {
}
};
3) Using a CSealed base class, protected ctor & virtual inheritance
class CSealed
{
protected:
CSealed() {
}
};
class CBase : virtual CSealed
{
public:
CBase() {
}
};
All the above methods make sure that CBase class cannot be inherited further. My Question is:
1) Which is the best method ? Any other methods available ?
2) Method 2 & 3 will not work unless the CSealed class is inherited virutally. Why is that ? Does it have anything to do with vdisp ptr ??
PS:
The above program was compiled in MS C++ compiler (Visual Studio). reference : http://www.codeguru.com/forum/archive/index.php/t-321146.html
As of C++11, you can add the final keyword to your class, eg
class CBase final
{
...
The main reason I can see for wanting to do this (and the reason I came looking for this question) is to mark a class as non subclassable so you can safely use a non-virtual destructor and avoid a vtable altogether.
这篇关于在C ++中防止类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!