如何在 C++ 中定义密封类?

2021-12-17 00:00:00 class inheritance c++ derived-class sealed

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

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:

  • final"的目的是什么?C++11 中函数的关键字?

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!

相关文章