在C++中,類型轉換運算符(type conversion operators)允許對象在不同類型之間進行轉換
int intValue = 42;
double doubleValue = static_cast<double>(intValue);
class Base { virtual ~Base() {} };
class Derived : public Base {};
Base* basePtr = new Derived();
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr); // 安全的轉換
const int constValue = 42;
int* intPtr = const_cast<int*>(&constValue); // 修改const屬性
int intValue = 42;
void* voidPtr = &intValue;
int* newIntPtr = reinterpret_cast<int*>(voidPtr); // 將void指針轉換為int指針
總之,在使用C++類型轉換運算符時,請確保了解轉換的含義,并確保轉換是安全的。在可能的情況下,使用靜態類型轉換運算符和動態類型轉換運算符,避免使用const類型轉換運算符和reinterpret_cast,因為它們可能導致未定義行為。