[C++] static_cast, dynamic_cast, reinterpret_cast, const_cast
static_cast(exp) function 可以將 exp 轉換成 new_type,但是不能夠確保轉換一定會成功,upcasting 一般可以成功,但是 downcasting 則需要確認是否轉換失敗。
struct B {};
struct D : B {};
int main(){
D d;
B br = d; // upcast via implicit conversion
D another_d = static_cast(br); // downcast
}
const_cast() function 可以將 const 變數的值做修改,new_type 必須要是a pointer, reference, or pointer to member to an object type。
void change(const int* p) {
int *v = const_cast(p);
*v = 20;
}
int main(){
const int* k1 = new int(1000);
int* k2 = new int(2000);
*k1 = 100; // Compling error
*k2 = 200;
cout << *k1 << " " << *k2 << endl;
change(k1);
change(k2);
cout << *k1 << " " << *k2 << endl;
}
output of the above codes:
1000 200
20 20