如何阻止一个类继承? [英] How to stop a class from being inheritance?

查看:74
本文介绍了如何阻止一个类继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据来自互联网的信息,有两种创建Final类的方法: -

1.在课名后使用final关键字(c ++ 11)

  class  end  final  
{};



2.通过创建一个带有私有构造函数的prefinal类,使最终类成为最终类的朋友,并在最终类中实际上继承了最终类。

< pre lang =c ++> class preFinal
{
preFinal(){}
朋友 FINAL;
};
class FINAL: virtual public preFinal // 没有类可以派生此类。
{
};
class 派生: public FINAL // 编译错误,preFinal类的私有构造函数
{};





但我能想到的第三个选项是,如果我们在私有中定义构造函数,那么我们也不能继承一个类,如下所示: -



  class 最终
{
Final(){}
};
派生: public Final { // 这将导致错误,因为最终构造函数是私有的。
};
int main()
{
Final fo;
}





我的尝试:



那么为什么我们需要最终关键字或创建预定级别(选项-2)?



任何人都可以让我知道我们的任何情况可以使用私有构造函数继承一个类吗?

解决方案

参见 final Specifier | Microsoft Docs [ ^ ]


谢谢理查德,

您发送给我最终关键字描述的链接。我想知道我是否私下定义构造函数以使类成为最终是否有任何错误。



BTW通过您的链接我也开始知道我们可以使用final关键字来防止派生类中的虚函数重载。所以我现在很清楚最终的关键字使用情况。但是,当我们通过将构造函数保持为私有来实现相同时,我们是否需要遵循上面提到的选项2?


如果您将构造函数设置为私有以使其成为最终,那么您将如何制作该课程的对象?



 class Final 
{
private:
Final(){ }
public:
//其他成员
};

void someFunc(){
Final myFinal; //编译错误
}


As per information from internet there are two ways create a Final class:-
1. by using "final" keyword after class name(c++11)

class end final
{ };


2. by creating a prefinal class with private constructor, making final class as friend of prefinal class and virtually inherit the prefinal class in final class.

class preFinal
{
  preFinal(){}
  friend class FINAL;
};
class FINAL:virtual public preFinal  //No class can derive this class.
{
};
class Derived:public FINAL //Compilation error,private constructor of preFinal class
{};



But third option I can think of is, if we define constructor in private itself then also we can't inherit a class, as below:-

class Final
{
   Final(){}
};
class Derived:public Final{  //This will give error as Final constructor is in private.
};
int main()
{
   Final fo;
}



What I have tried:

Then why we need final keyword or to create prefinal class(option-2)?

Can anyone please let me know any case in which we can inherit a class with private constructor?

解决方案

See final Specifier | Microsoft Docs[^]


Thanks Richard,
You send me link for final keyword description. I wanted to know if I define the constructor in private to make a class as final is there any thing wrong in it.

BTW through your link I also came to know that we can use "final" keyword for preventing virtual function over-riding in derived class. So I am clear about final keyword usage now. But do we need to follow option 2 I mentioned above when we can achieve the same by just keeping constructor in private?


If you are making constructor as private to make it final, how you will make the object of that class?

class Final
{
private:
  Final(){}
public:
  // other members
};

void someFunc() {
   Final myFinal; // compilation error
}


这篇关于如何阻止一个类继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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