解决方法
This is kNown as making the class
“final” or “a leaf.” There are three
ways to do it: an easy technical
approach,an even easier non-technical
approach,and a slightly trickier
technical approach.The (easy) technical approach is to
make the class’s constructors private
and to use the 07001
to create the objects. No one can
create objects of a derived class
since the base class’s constructor
will be inaccessible. The “named
constructors” themselves Could 07002 or they Could 07003.The (even easier) non-technical
approach is to put a big fat ugly
comment next to the class deFinition.
The comment Could say,for example,//
or even just
We'll fire you if you inherit from
this class/*final*/
. Some
class Whatever {...};
programmers balk at this because it is
enforced by people rather than by
technology,but don’t knock it on face
value: it is quite effective in
practice.A slightly trickier technical approach
is to exploit 07004.
Since 07005,the following
guarantees that no concrete class can
inherit from classFred
:
class Fred; class FredBase { private: friend class Fred; FredBase() { } }; class Fred : private virtual FredBase { public: ... };
Class
Fred
can accessFredBase
‘s ctor,
sinceFred
is a friend ofFredBase
,
but no class derived from Fred can
access FredBase’s ctor,and therefore
no one can create a concrete class
derived fromFred
.If you are in extremely
space-constrained environments (such
as an embedded system or a handheld
with limited memory,etc.),you should
be aware that the above technique
might add a word of memory to
sizeof(Fred)
. That’s because most compilers implement virtual inheritance by adding a pointer in objects of the derived class. This is compiler specific; your mileage may vary.
原文地址:https://www.jb51.cc/c/116854.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。