如何阻止该类被其他类继承.
How to stop the class to be inherited by other class.
在 C++11 中,你可以在定义中使用 final
关键字来封装一个类:
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
所以我们可以利用模板使Usable_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++ 中定义密封类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!