看代码注释即可
#include <iostream>
class A
{
public:
virtual void func() {
std::cout << "I'm A" << std::endl;
}
};
class B :public A
{
public:
virtual void func() {
std::cout << "I'm B" << std::endl;
}
};
/*******************************************************
基本数据类型之间的转换使用,例如float转int,int转char等,在有类型指针和void*之间转换使用,
子类对象指针转换成父类对象指针也可以使用static_cast。非多态类型转换一般都使用static_cast,
而且最好把所有的隐式类型转换都是用static_cast进行显示替换
********************************************************/
void test1()
{
double a = 10.03;
int b = static_cast<int>(a);
std::cout << b << std::endl;
//int* p = static_cast<int*>(a); //error 不能使用static_cast在有类型指针之间进行类型转换
int* p = reinterpret_cast<int*>(&a);//类似于c的万能转换
B c;
A* d = static_cast<B*>(&c);//多态 基类指针指向派生类对象
d->func();
}
/*******************************************************
用于将父类的指针或引用转换为子类的指针或引用,此场景下父类必须要有虚函数,
因为dynamic_cast是运行时检查,检查需要运行时信息RTTI,而RTTI存储在虚函数表中
********************************************************/
void test2()
{
B b;
b.func();
A* a = dynamic_cast<A*>(&b);
a->func();
B* c = dynamic_cast<B*>(a);
c->func();
}
void test3()
{
int data = 10;
const int* cpi = &data;
int* pi = const_cast<int*>(cpi);
const int* cpii = const_cast<const int*>(pi);
}
int main()
{
// test1();//static_cast reinterpert_cast
// test2();//dynamic_cast
// test3();//const_cast
return 0;
}