#include <iostream>
// type casting.
// static_cast: will do compile time checking.
// dynamic_cast: will do run time checking, it'a great way to see if it's actually worked.
// const_cast: to add or remove const.
// reinterpret_cast: basically like what you did in TypePunning.
class Base
{
public:
Base() {}
virtual ~Base() {}
};
class Derived : public Base
{
public:
Derived() { }
~Derived() { }
};
class AnotherClass : public Base
{
public:
AnotherClass() { }
~AnotherClass() { }
};
int main(void)
{
double value = 5.25;
double a = (int)value + 5.3; //c style cast.
double b = static_cast<int>(value) + 5.3; //cpp style cast, make your code more solid.
Derived* derived = new Derived();
Base* base = derived;
AnotherClass* anotherClass = dynamic_cast<AnotherClass*>(base);
if (!anotherClass)
{
std::cout << "dynamic_cast<AnotherClass*>(base) is failed!\n";
}
Derived* de = dynamic_cast<Derived*>(base);
if (de)
{
std::cout << "dynamic_cast<Derived*>(base) is successful!\n";
}
std::cin.get();
}
【Cherno的C++视频】Casting in C++
最新推荐文章于 2024-09-07 10:59:43 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)