介绍
无
Demo
#include <iostream>
void static_cast_test()
{
int n = 5;
float f = n; // C
float f2 = static_cast<float>(n); // C++
//5 5
std::cout << f << " " << f2 << std::endl;
}
void reinterpret_cast_test()
{
int n = 5;
int* p = (int*)n; // C
int* p2 = reinterpret_cast<int*>(n);// C++
//5 5
std::cout << p << " " << p2 << std::endl;
}
void const_cast_test()
{
const int n = 5;
//C
int* p = (int*)&n;
*p = 3;
//C++
int* p2 = const_cast<int*>(&n);
*p2 = 2;
//5 2 2
std::cout << n << " " << *p << " " << *p2 << std::endl;
}
class Base
{
public:
virtual void Print()
{
std::cout << "Base Print()" << std::endl;
}
};
class Inheritor : public Base
{
public:
virtual void Print()
{
std::cout << "Inheritor Print()" << std::endl;
}
};
void dynamic_cast_test()
{
Base b;
Inheritor i;
Base* pb;
Inheritor* pi;
pi = &i;
pb = dynamic_cast<Base*>(pi);
pb->Print(); //Inheritor
pb = &i;
pi = dynamic_cast<Inheritor*>(pb);
pi->Print(); //Inheritor
pb = &b;
pi = dynamic_cast<Inheritor*>(pb);
//pi->Print(); ERROR pi = NULL
}
int main()
{
static_cast_test();
reinterpret_cast_test();
const_cast_test();
dynamic_cast_test();
return 0;
}