C++ type conversation

Type conversation

1. const_cast: convert between const and non-const

    char *p1 = new char[6];
    strcpy(p1,"Hello");

   
    const char *p2 = p1;
               char *p3 = const_cast< char *>(p2);
    const char *p4 = const_cast< const char *>(p3);

    p2[2] = 'U';   // it will report violate with a const variable
    p3[2] = 'U';   // it's OK
    p4[2] = 'U';   // it will report violate with a const variable
   

2. static_cast: C-stype type conversation
   Any type conversions that the compiler performs implicitly can be made explicit through use of a
static_cast.


3. reinterpret_cast: it's used only between pointer type or pointer and integer type(becase int type is some like a pointer)
   it will reinterpret bitmap of object.
 
   A reinterpret_cast generally performs a low-level reinterpretation of the bit pattern of its operands,
and its correctness in large part depends on the active management of the programmer. For example, in the
following cast


4. dynamic_cast: used main between base class and inherit class
   A dynamic_cast operator can be used to convert a pointer that refers to an object of class type to a
pointer to a class in the same class hierarchy. A dynamic_cast operator can also be used to convert an
lvalue for an object of class type to a reference to a class in the same class hierarchy. Unlike the other casts
supported in C++, a dynamic_cast is a cast that is performed at run-time. If the pointer or lvalue
operand cannot be cast to the target type of the conversion, the dynamic_cast fails. If a
dynamic_cast to a pointer type fails, the result of the dynamic_cast is the value 0. If a
dynamic_cast to a reference type fails, an exception is thrown.

   -- dynamic_cast< Type* >( pe )
   -- dynamic_cast< Type& >( lval )

class employee {
public:
       virtual int salary();
};

class manager : public employee {
public:
       int salary();
};

class programmer : public employee {
public:
       int salary();
       int bonus();
};


void payroll( employee *pe )
{
     programmer *pm = dynamic_cast< programmer* >( pe );
     if ( pm ) {
        // to do
     } else {
        // to do
     }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值