2008 March 21th Friday (三月 二十一日 金曜日)

C++ has three components supporting RTTI:

  The dynamic_cast operator generates a pointer to a derived type from a pointer to a base type, if possible. Otherwise, the operator returns 0,
  the null pointer.

  The typeid operator returns a value identifying the exact type of an object.

  A type_info structure holds information about a particular type.

  The static_cast operator has the same syntax as the others:

static_cast < type-name > (expression)

It's valid only if type_name can be converted implicitly to the same type expression has, or vice versa. Otherwise, the cast is an error. Suppose High is a base class to Low and that Pond is an unrelated class. Then conversions from High to Low and Low to High are valid, but a conversion from Low to Pond is disallowed:

High bar;
Low blow;
...
High * pb = static_cast (&blow);     // valid upcast
Low * pl = static_cast (&bar);        // valid downcast
Pond * pmer = static_cast (&blow);   // invalid, Pond unrelated

dynamic_cast < type-name > (expression)

  To summarize, suppose High and Low are two classes, that ph is type High * and pl is type Low *. Then the statement

pl = dynamic_cast ph;

  assigns a Low * pointer to pl only if Low is an accessible base class (direct or indirect) to High. Otherwise, the statement assigns the null pointer to pl.

  The purpose of this operator is to allow upcasts within a class hierarchy (such type casts being safe because of the is-a relationship) and to disallow other casts.

  During experiment, I found the upcast (cast a type from a derived class to an accessible base class) is all right; however, the downcast (cast a type from a
base class to a derived class) is also past by gcc compiler with a waring which tell you that cast can never succeed.

  About how to use a pointer to a member or to a method in class, the example is as follow.

#include

using namespace std;

class A{
public:
int m;

A(){ m = 8848; }
int getM() {return m;}
};

class B: public A{
public:
B(){}
};

int main(){
A a;
B *bp = new B();

int (A::*amp) = &A::m;
int (B::*bmp) = amp;
cout<<"A pointer to a member. "<*bmp<
int (A::*afp)() = &A::getM;
int (B::*bfp)() = afp;
cout<<"A pointer to a method. "<<(bp->*bfp)()<
return 0;
}

你可能感兴趣的:(class,hierarchy,components,structure,compiler,null)