防止 C++ 中的类继承

Prevent class inheritance in C++(防止 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:

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Why should I declare a virtual destructor for an abstract class in C++?(为什么要在 C++ 中为抽象类声明虚拟析构函数?)
Why is Default constructor called in virtual inheritance?(为什么在虚拟继承中调用默认构造函数?)
C++ cast to derived class(C++ 转换为派生类)
C++ virtual function return type(C++虚函数返回类型)
Is there any real risk to deriving from the C++ STL containers?(从 C++ STL 容器派生是否有任何真正的风险?)
How does virtual inheritance solve the quot;diamondquot; (multiple inheritance) ambiguity?(虚拟继承如何解决“钻石问题?(多重继承)歧义?)