RTTI implementation of a single inheritance system (according to class judgment "pointer)

xiaoxiao2021-03-06  90

In MFC, we have seen the implementation of RTTI in the MFC. In the MFC, the RTTI functionality implemented using cruntimeclass and declare_dynamic and declare_implement macro is quite powerful, but in our general program, there is still a complex RTTI in the C standard. The rtti support provided by TypeID operators and Type_info information is quite simple, just simple comparison of two type objects and pointers belong to the same class; and for our usual simple applications, these are sufficient; to use C standards The RTTI feature provided must require the compiler to open the GR compilation option, but in some embedded development, we cannot use this compile option, then we have to simulate an RTTI, the following is one of my implementation: it According to a class Inheriting the name of the class to determine which class belongs to which class is belonging, relying on virtual functions to complete the function, and finally abstract to a macro implementing the entire RTTI. The specific code is as follows:

// Use this macro to generate a virtual function that returns a class name for our class

#define declare_rtti (classname) /

PUBLIC: /

Virtual Pchar getClassName () /

{/

Return #classname; /

}

The base class in the // class system, implements an iskindof method, can determine the class according to the class name

Class Base

{

DECLARE_RTTI (BASE)

PUBLIC:

Bool iskindof (Pchar szclassname)

{

IF (0 == Strcmp (getclassname (), szclassname))

{

Return True;

}

Return False;

}

}

//Derived class

Class Derive: Public Base

{

DECLARE_RTTI (Derive)

PUBLIC:

}

// This function only gives a base class pointer, which can be known from this pointer to which one is

Void test (base * p)

{

IF (p-> iskindof ("base")))

{

Printf ("This Is The Base Class Pointer! / N");

}

Else IF (P-> Iskindof ("Derive"))

{

Printf ("This Is The Derive Class Pointer! / N");

}

Else

{

Printf ("This Is The New Derived Class:% S / N", P-> getClassName ());

}

}

//Derived class

Class Deriveex: Public Derive

{

Declare_rtti (deriveex)

}

Int main (int Argc, char * argv [])

{

DeriveEx Obj; // You can change the class here and see the output result.

TEST (& obj);

}

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

New Post(0)