作者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