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

43 lines
1.2 KiB
C++
Raw Permalink 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的区别并给出示例代码进行说明。
// static_cast :
// 静态转换,用于基本类型的转换、隐式转换、向上转换和非多态类之间的转换。它在编译时进行类型检查,并且只能用于具有相关性的类型之间的转换。因为没有运行时类型检查,不能用于多态类的向下转换(即将基类指针或引用转换为派生类指针或引用)。
#include <iostream>
using namespace std;
int num = 10;
double res = static_cast<double>(num); // 将整数类型转换为浮点数类型
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 = static_cast<Derived *>(p); // 向下转换,不安全
dp->bar(); // 但是可以调用派生类的成员函数
dp->foo();
return 0;
}