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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理