How to make a class can't be inherited in C ++

zhaozj2021-02-16  51

[C implementation Sealed class] Today, I saw "Software R & D 5" has an article translated from cuj "to make the class can not inherit", the method is very good, but there are several problems: 1. It is said that the translator is said, there is still a way to carry Inherit, although the method is a bit metamorphosis 2. The most important problem is, this approach will cause time overhead. Because at least the VTABLE pointer will be added. Therefore, for the above two problems, changes were made as follows: #ifdef _DEBUG namespace internalSealed {template class Class_Is_Sealed {protected: Class_Is_Sealed () {};};}; template class Sealed: private virtual INTERNALSEALED :: Class_is_sealed {Friend TypeName T;}; #else template Class Sealed}; #ENDIF like this, in Debug mode, as long as a class is inherited from Sealed , it is no longer inherit. At the same time, in the Release mode, since it is no longer inspected whether it can be inherited, no overhead is generated (empty class is optimized by the compiler). Example: #include "Sealed.h" Class Test: Sealed {public: int print () {Return 1;}}; Class TTT: Public Test //, Sealed , Sealed {public : Int print () {return 2;}}; int main (int Argc, char * argv []) {test t; printf ("% d / n", t.print ()); ttt t1; // compile Error Printf ("% D / N", T1.Print ());

Return 0;}

转载请注明原文地址:https://www.9cbs.com/read-20873.html

New Post(0)