close
http://windsplife.blogspot.tw/2010/09/cstaticcast-dynamiccast-reinterpretcast.html
[C++] 標準類型轉換:static_cast, dynamic_cast, reinterpret_cast, and const_cast
1
2
3
4
5
6
7
8
9
10
11
12
|
#include <iostream> using namespace std; int main() { int * i; char * str = "test" ; i = reinterpret_cast < int >(str); cout << i << endl; return 0; } |
- static_cast
- 可用於轉換基底類別指標為衍生類別指標,也可用於傳統的資料型態轉換。
- 舉例來說,在指定的動作時,如果右邊的數值型態比左邊的數值型態型態長度大時,超出可儲存範圍的部份會被自動消去,例如將浮點數指定給整數變數,則小數的部份會被自動消去,例子如下,程式會顯示3而不是3.14:
1234
int
num = 0;
double
number = 3.14;
num = number;
cout << num;
1234int
num = 0;
double
number = 3.14;
num =
static_cast
<
int
>(number);
</
int
>
12int
number = 10;
cout <<
static_cast
<
double
>(number) / 3;
12int
number = 10;
cout << (
double
) number/ 3;
- dynamic_cast
- 使用static_cast(甚至是傳統的C轉型方式)將基底類別指標轉換為衍生類別指標,這種轉型方式稱為強制轉型,但是在執行時期使用強制轉型有危險性,因為編譯器無法得知轉型是否正確,執行時期真正指向的物件型態是未知的,透過簡單的檢查是避免錯誤的一種方式:
1234
if
(
typeid
(*base) ==
typeid
(Derived1)) {
Derived1 *derived1 =
static_cast
<derived1*>(base);
derived1->showOne();
}
12345678910void
showWho(Base *base) {
base->foo();
if
(Derived1 *derived1 =
dynamic_cast
>derived1*<(base)) {
derived1->showOne();
}
else
if
(Derived2 *derived2 =
static_cast
>derived2*<(base)) {
derived2->showTwo();
}
}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950#include <iostream>
#include <typeinfo>
using
namespace
std;
class
Base {
public
:
virtual
void
foo() = 0;
};
class
Derived1 :
public
Base {
public
:
void
foo() {
cout <<
"Derived1"
<< endl;
}
void
showOne() {
cout <<
"Yes! It's Derived1."
<< endl;
}
};
class
Derived2 :
public
Base {
public
:
void
foo() {
cout <<
"Derived2"
<< endl;
}
void
showTwo() {
cout <<
"Yes! It's Derived2."
<< endl;
}
};
void
showWho(Base &base) {
try
{
Derived1 derived1 =
dynamic_cast
<derived1&>(base);
derived1.showOne();
}
catch
(bad_cast) {
cout <<
"bad_cast 轉型失敗"
<< endl;
}
}
int
main() {
Derived1 derived1;
Derived2 derived2;
showWho(derived1);
showWho(derived2);
return
0;
}
Yes! It's Derived1.
執行結果(使用static_cast):
bad_cast 轉型失敗Yes! It's Derived1.
Yes! It's Derived1. - reinterpret_cast
- 用於將一種型態的指標轉換為另一種型態的指標,例如將char*轉換為int*
- (可能)執行結果:
134514704
- const_cast
- const_cast用於一些特殊場合可以覆寫變數的const屬性,利用cast後的指標就可以更改變數的內部。
- 使用格式:
1
const_cast
<常量(
const
)型態(指標) / 非常量型態(指標)>( 非常量變數(指標) / 常量變數(指標) );
123456789101112131415161718192021#include <iostream>
using
namespace
std;
void
foo(
const
int
*);
int
main() {
int
var = 10;
cout << var << endl;
foo(&var);
cout << var << endl;
return
0;
}
void
foo(
const
int
* p) {
int
*v =
const_cast
<
int
*>(p);
*v = 20;
}
10
20
全站熱搜