語法(Syntax) :
static_cast < new_type > ( expression )
Returns a value of type new_type.
1. 可用在很多種情況 但是無法去除(constness or volatility. ),最常見的是implicit conversition
例如將float 轉型成 int
int main()
{
// initializing conversion
int n = static_cast<int>(3.14);
std::cout << "n = " << n << '\n';
// 一般來說,我們通常都會直接偷懶,寫成這樣
// int n = (int)3.14;
std::vector<int> v = static_cast<std::vector<int>>(10);
std::cout << "v.size() = " << v.size() << '\n';
system("PAUSE");
}
輸出:
n = 3 v.size() = 10
2. Downcast: 向下轉型
這樣的需求在C++開發當中常常需要用到,但是必須要特別注意,若使用static_cast則於runtime期間並不會自行做檢查,必須仰賴開法者自行處理(參考static polymorphism),所以是可能發生致命錯誤哦,一般都會建議使用比較安全的 dynamic_cast 作法來進行downcast 。
#include <iostream>
struct CShape {
int m = 0;
void hello() const {
std::cout << "Hello world, this is CShape!\n";
}
};
struct CCircle : CShape {
void hello() const {
std::cout << "Hello world, this is CCircle!\n";
}
};
int main()
{
// static downcast
CShape shape;
CShape& rshape = shape; // upcast via implicit conversion
rshape.hello();
CCircle& another_Circle = static_cast<CCircle&>(rshape); // downcast
another_Circle.hello();
system("PAUSE");
}
輸出:
Hello world, this is CShape! Hello world, this is CCircle!
3. 轉換 lvalue-to-rvalue, array-to-pointer, or function-to-pointer
struct B {
int m = 0;
void hello() const {
std::cout << "Hello world, this is B!\n";
}
};
struct D : B {
void hello() const {
std::cout << "Hello world, this is D!\n";
}
};
int main()
{
//array - to - pointer followed by upcast
D a[10];
B* dp = static_cast<B*>(a);
system("PAUSE");
}
4. 轉換 scoped enum 為 int 或是 float
enum class E { ONE = 1, TWO, THREE };
enum EU { ONE = 1, TWO, THREE };
int main()
{
E e = E::ONE;
int one = static_cast<int>(e);
std::cout << one << '\n';
// int to enum, enum to another enum
E e2 = static_cast<E>(one);
EU eu = static_cast<EU>(e2);
system("PAUSE");
}
文章標籤
全站熱搜
