C++ 类型转换

普通类型

类类型

对于类类型,编译器只能自动执行一步隐式类型转换.例如从字符串字面值转换为string类型,但是无法继续将string隐式转换为其他类型

新式显示类型转换

格式

cast-name(expression);

static_cast

Any well-defined type conversion, other than those involving low-level const, can be requested using a static_cast.

// i and j are both int type,
double slope = static_cast<double>(j) / i; 

// perform a conversion that the compiler will not generate automatically.
// converts void * back to the original pointer type
void * p = &d;
double * dp = static_cast<double * >(p);

const_cast

const_cast only be used to change the constness of an expression.

It is different from the static_cast, which only be used to change the type of an expression.
i.e. if we use static_cast to change the constness of an expression or const_cast to change the type of an expression, we will get a compile-time error.

const char * cp; 

// error: static_cast can’t cast away const
char * q = static_cast<char * >(cp);

// error: const_cast only changes constness
const_cast<string>(cp);

reinterpret_cast

performs a low-level reinterpretation of the bit pattern of its operands.

int * ip; 
char * pc = reinterpret_cast<char * >(ip);

It is worth noting that reinterpret_cast is dangerous. As the following code shows.

int * ip; 
char * pc = reinterpret_cast<char * >(ip);
string str(pc);

We ought to know that no matter what type of pointer it is, the pc itselt is just a address(a number) and the type shows the type of object addressed by this pointer.
So the actual object addressed by pc is an int, not a character. Any use of pc that assumes it’s an ordinary character pointer is likely to fail at run time.
But about string str(pc), the compiler has no way of knowing that it actually holds a pointer to an int. Thus, the initialization of str with pc is absolutely correct—albeit in this case meaningless or worse.

dynamic_cast

posted @ 2023-06-18 19:35  0x7F  阅读(5)  评论(0编辑  收藏  举报