您的位置:首页 > 编程语言 > C语言/C++

C++ type conversation

2008-03-25 14:52 666 查看
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
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: