C++指针强转问题 static_cast dynamic_cast reinterpret_cast const_cast
·
#static_cast #dynamic_cast #reinterpret_cast #const_cast
MFC中常见的多线程或窗口消息用法:
// 启动线程时
AfxBeginThread(ThreadProc, reinterpret_cast<LPVOID>(this));
// 线程函数
UINT ThreadProc(LPVOID pParam)
{
CMyWnd* pWnd = reinterpret_cast<CMyWnd*>(pParam);
if (pWnd)
{
pWnd->DoSomething();
}
return 0;
}
MyMessage* pMsg = new MyMessage;
::SendMessage(hWnd, WM_USER_MYMSG, reinterpret_cast<WPARAM>(pMsg), 0);
MyMessage* pMsg = reinterpret_cast<MyMessage*>(wParam);
if (!pMsg) return;
C++中父子类强转
// static_cast 子类 → 父类
double d = 3.14;
int i = static_cast<int>(d); // 安全,丢失小数部分
class Base {};
class Derived : public Base {};
Derived d1;
Base* bp = static_cast<Base*>(&d1); // 向上转型安全
// dynamic_cast 父类 → 子类
class Base { virtual ~Base(){} };
class Derived : public Base {};
Base* bp = new Derived;
Derived* dp = dynamic_cast<Derived*>(bp); // 成功,dp != nullptr
// reinterpret_cast 不确定时(慎用)
int i = 0x12345678;
char* p = reinterpret_cast<char*>(&i);
// p 指向 i 的首字节,能逐字节访问
常见用途:
1.整型 ↔ 指针
2.不相关类型的指针互转(例如 char* ↔ int*)
3.用于底层系统编程(如驱动、序列化、硬件寄存器操作)
⚠️ 慎用!可能导致未定义行为,尤其是违反内存对齐时。
// const_cast 用于去掉 const 或 volatile 限定符
void print(char* str) { /* ... */ }
const char* s = "hello";
print(const_cast<char*>(s)); // 去掉 const,调用兼容函数
作用:
1.用于去掉 const 或 volatile 限定符。
2.不能改变对象本身的常量性(即:原本定义为 const 的对象,改了就是未定义行为)。
更多推荐



所有评论(0)