#include <iostream>
using namespace std;
class Person
{
public:
int m_a;
};
class Student
{
public:
int m_b;
};
int main()
{
Person p;
Student s;
Person* p1 = &p;
Student* s1 = &s;
//Student *s3 = static_cast<Student*>(p1); //编译时就检测,不能转换
Student *s2 = (Student*)(p1); //父类转子类,可以但是越界访问了,严重的会引起崩溃,因为父类没有子类的属性m_b
s2->m_b = 2;
return 0;
}
dynamic_cast
#include <iostream>
using namespace std;
class Person
{
public:
virtual void SayHello()
{
}
int m_a;
};
class Student
{
public:
virtual void SayHello()
{
}
int m_b;
};
int main()
{
Person p;
Student s;
Person* p1 = &p;
Student* s1 = &s;
//编译是通过的,运行时检测是否真正转换成功
//此时p1位父类指针,将父类指针转换为子类指针,这里得到的是nullptr,即转换不成功,避免了可能的崩溃
//此外,dynamic_cast,还要要求,父类有虚函数,才行否则编译时就报错了。
//也就是说,dynamic_cast用于运行时检测,指针之间是否转换成功,这样就安全了一点。
Student *s2 = dynamic_cast<Student*>(p1);
if (s2 != nullptr)
{
cout << "succeed" << endl;
}
return 0;
}