防止 C++ 中的类继承 [英] Prevent class inheritance in C++

查看:43
本文介绍了防止 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:

  1. 哪种方法最好?还有其他方法吗?

  1. 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++ 中的类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆