如何在 C++ 中定义密封类? [英] How to define sealed class in C++?

查看:40
本文介绍了如何在 C++ 中定义密封类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何阻止该类被其他类继承.

How to stop the class to be inherited by other class.

推荐答案

C++11 解决方案

在 C++11 中,你可以在定义中使用 final 关键字来封装一个类:

C++11 solution

In C++11, you can seal a class by using final keyword in the definition as:

class A final  //note final keyword is used after the class name
{
   //...
};

class B : public A  //error - because class A is marked final (sealed).
{                   //        so A cannot be derived from.
   //...
};

要了解 final 的其他用途,请在此处查看我的回答:

To know the other uses of final, see my answer here:

Bjarne Stroustrup 的代码:我可以阻止人们从我的班级?

class Usable;
class Usable_lock {
    friend class Usable;
private:
    Usable_lock() {}
    Usable_lock(const Usable_lock&) {}
};

class Usable : public virtual Usable_lock {
public:
    Usable();
    Usable(char*);
};
Usable a;

class DD : public Usable { };

DD dd;  // error: DD::DD() cannot access
        // Usable_lock::Usable_lock(): private  member


Generic_lock

所以我们可以利用模板使Usable_lock足够通用以密封任何类:


Generic_lock

So we can make use of template to make the Usable_lock generic enough to seal any class:

template<class T>
class  Generic_lock 
{
    friend T;
    Generic_lock() {}                     //private
    Generic_lock(const Generic_lock&) {}  //private
};

class Usable : public virtual Generic_lock<Usable>
{
public:
    Usable() {}
};

Usable a; //Okay
class DD : public Usable { };

DD dd; //Not okay!

这篇关于如何在 C++ 中定义密封类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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