42 lines
1.2 KiB
C++
42 lines
1.2 KiB
C++
|
// 请简述static_cast、dynamic_cast和reinterpret_cast的区别,并给出示例代码进行说明。
|
|||
|
|
|||
|
// dynamic_cast :
|
|||
|
// 动态转换,用于多态类之间的转换,即在基类指针或引用和派生类指针或引用之间进行转换。它在运行时进行类型检查,如果转换是安全的,则返回转换后的指针或引用;如果转换不安全,则返回空指针或引用。dynamic_case 只能用于具有虚函数的类之间的转换。
|
|||
|
|
|||
|
#include <iostream>
|
|||
|
|
|||
|
using namespace std;
|
|||
|
|
|||
|
class Base
|
|||
|
{
|
|||
|
public:
|
|||
|
virtual void foo() { cout << "基类 foo() 函数" << endl; }
|
|||
|
};
|
|||
|
|
|||
|
class Derived : public Base
|
|||
|
{
|
|||
|
public:
|
|||
|
void bar() { cout << "派生类 bar() 函数" << endl; }
|
|||
|
void foo() { cout << "派生类 foo() 函数" << endl; }
|
|||
|
};
|
|||
|
|
|||
|
int main()
|
|||
|
{
|
|||
|
Base *p = new Derived();
|
|||
|
Derived *dp = dynamic_cast<Derived *>(p); // 向下转换,安全
|
|||
|
|
|||
|
dp->bar(); // 可以调用派生类的成员函数
|
|||
|
dp->foo(); // 可以调用派生类的虚函数
|
|||
|
|
|||
|
Base *p1 = new Base();
|
|||
|
Derived *dp1 = dynamic_cast<Derived *>(p1); // 向下转换,不安全
|
|||
|
dp1->bar();
|
|||
|
// dp1->foo();
|
|||
|
|
|||
|
Derived *dp2 = new Derived();
|
|||
|
Base *p2 = dynamic_cast<Base *>(dp2); // 向上转换,安全
|
|||
|
p2->foo();
|
|||
|
|
|||
|
return 0;
|
|||
|
}
|