本文介绍了如何在C ++中定义密封类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何停止其他类继承的类。
解决方案
C ++ 11解决方案
在C ++ 11中,可以通过在定义中使用 final
关键字来封装类:
class A final //注释在类名后面使用final关键字
{
// ...
} ;
class B:public A //错误 - 因为类A被标记为final(sealed)。
{//所以A不能派生自。
// ...
};
要知道final的其他用法,请参见我的回答:
C ++ 03解决方案
:可以
class Usable;
类Usable_lock {
friend class Usable;
private:
Usable_lock(){}
Usable_lock(const Usable_lock&){}
};
类可用:public virtual Usable_lock {
public:
Usable();
Usable(char *);
};
可用a;
class DD:public Usable {};
DD dd; //错误:DD :: DD()无法访问
// Usable_lock :: Usable_lock():private member
b $ b
Generic_lock
所以我们可以使用模板来使 Usable_lock
通用以封闭任何类:
模板< class T&
class Generic_lock
{
friend T;
Generic_lock(){} // private
Generic_lock(const Generic_lock&){} // private
};
class可用:public virtual Generic_lock< Usable>
{
public:
Usable(){}
};
可用a; // Okay
class DD:public Usable {};
DD dd; //不行!
How to stop the class to be inherited by other class.
解决方案
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.
//...
};
To know the other uses of final, see my answer here:
C++03 solution
Bjarne Stroustrup's code : Can I stop people deriving from my class?
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
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 ++中定义密封类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!