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<High *> (&blow);     // valid upcast
Low * pl = static_cast<Low *> (&bar);        // valid downcast
Pond * pmer = static_cast<Pond *> (&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<Low *> 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 <iostream>

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. "<<bp->*bmp<<endl;

int (A::*afp)() = &A::getM;
int (B::*bfp)() = afp;
cout<<"A pointer to a method. "<<(bp->*bfp)()<<endl;

return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值