作者popo4231 (小泰)
看板EE_DSnP
標題Re: [問題] about casting
時間Tue Jan 15 22:20:46 2008
※ 引述《bumpwy (bumpwy)》之銘言:
what is the difference between " dynamic_cast" and "static_cast" ???
not a big question though.....
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.137.131.62
dynamic_cast是會去檢查cast的合法性的
你只能往inheritance hierarchy 的上游去轉換
dynamic_cast會recognize pointer所指的object
當你cast到它的derived class以下
dynamic_cast會return NULL
而static_cast卻只是轉換,不會幫你檢查
而且並不是所有型態都可以互轉
前提是要有內建的cast overloading函式
對於user-defined data type則要自己overload
e.g.
class A
{
public:
operator int() const
{
return _id;
}
private:
int _id;
};
這樣就可以轉int
cast另外有兩種
const_cast
是專門對付const ref,ptr to const用的
它可以把const specifier 效果去除
e.g.
int main()
{
const int i = 10;
const int& ref = i;
const_cast<int&>(ref) = 100;
const int* ptr = new int(1000);
*const_cast<int*>(ptr) = 10000;
while(true);
}
reinterpret_cast
專門對付不相干型態之指標互轉,連const都可以對付
e.g.
int main()
{
fstream fs("XDRZ.txt",ios::out);
string str = "abcdefg";
fs.write(reinterpret_cast<const char*>(&str),str.length());
while(true);
}
大致上是這樣
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.241.177
※ 編輯: popo4231 來自: 140.112.241.177 (01/15 22:23)
1F:推 bumpwy:真是多謝這位大強者 01/15 22:41
2F:→ bumpwy:可是對於往上游去轉換的意思有點不懂..... 01/15 22:44