qfedu-cpp-level/day7/homework/h2_2.cpp

42 lines
1.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 请简述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;
}