C++ type conversation

编程知识 更新时间:2023-05-02 21:13:30
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
     }
}

更多推荐

C++ type conversation

本文发布于:2023-04-28 16:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/e04db1279bf6f933dcbb2ce0881975e1.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:type   conversation

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 109208文章数
  • 27719阅读数
  • 0评论数