Prevent class inheritance in C++(防止 C++ 中的类继承)
问题描述
最近我的一位朋友问我如何防止 C++ 中的类继承.他希望编译失败.
Recently one of my friend asked me how to prevent class inheritance in C++. He wanted the compilation to fail.
我想了想,找到了 3 个答案.不确定哪个是最好的.
I was thinking about it and found 3 answers. Not sure which is the best one.
1) 私有构造函数
class CBase
{
public:
static CBase* CreateInstance()
{
CBase* b1 = new CBase();
return b1;
}
private:
CBase() { }
CBase(CBase3) { }
CBase& operator=(CBase&) { }
};
2) 使用 CSealed
基类,私有构造函数 &虚拟继承
2) Using CSealed
base class, private ctor & virtual inheritance
class CSealed
{
private:
CSealed() {
}
friend class CBase;
};
class CBase : virtual CSealed
{
public:
CBase() {
}
};
3) 使用 CSealed
基类,受保护的构造函数 &虚拟继承
3) Using a CSealed
base class, protected ctor & virtual inheritance
class CSealed
{
protected:
CSealed() {
}
};
class CBase : virtual CSealed
{
public:
CBase() {
}
};
以上所有方法确保CBase
类不能被进一步继承.我的问题是:
All the above methods make sure that CBase
class cannot be inherited further.
My Question is:
哪种方法最好?还有其他方法吗?
Which is the best method ? Any other methods available ?
方法 2 &除非 CSealed
类被虚拟继承,否则 3 将无法工作.这是为什么 ?和vdisp ptr有关系吗??
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 ??
附注:
以上程序是在 MS C++ 编译器 (Visual Studio) 中编译的.参考:http://www.codeguru.com/forum/存档/index.php/t-321146.html
The above program was compiled in MS C++ compiler (Visual Studio). reference : http://www.codeguru.com/forum/archive/index.php/t-321146.html
推荐答案
从 C++11 开始,您可以将 final 关键字添加到您的类中,例如
As of C++11, you can add the final keyword to your class, eg
class CBase final
{
...
我可以看到想要这样做的主要原因(以及我来寻找这个问题的原因)是将类标记为不可子类化,以便您可以安全地使用非虚拟析构函数并完全避免使用 vtable.
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++ 中的类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:防止 C++ 中的类继承


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09