static_cast(编译阶段)
- 用于类型相关的指针之间相互转换
- 用于基本类型的数据之间进行类型转换
#include <iostream>
class Base
{
public:
int a;
};
class Derived : public Base
{
public:
int b;
};
int main()
{
Derived *p1 = new Derived();
Base *p2 = static_cast<Base*>(p1);
Base *p3 = new Base();
Derived *p4 = static_cast<Derived*>(p3);
int aa = 10;
double bb = static_cast<double>(aa);
double cc = 3.14f;
int dd = static_cast<int>(cc);
}
dynamic_cast(运行阶段)
- 运行阶段执行类型检查
#include <iostream>
using namespace std;
class Fish
{
public:
virtual void swim()
{
cout << "Fish swim in water" << endl;
}
virtual ~Fish()
{}
};
class Tuna : public Fish
{
public:
void swim()
{
cout << "tuna swims real fast in the sea" << endl;
}
};
class Carp : public Fish
{
public:
void swim()
{
cout << "carp swims real slow in the lake" << endl;
}
};
void DetectFishType(Fish *fish)
{
Tuna* p1 = dynamic_cast<Tuna *>(fish);
if (p1)
p1->swim();
Carp* p2 = dynamic_cast<Carp *>(fish);
if (p2)
p2->swim();
}
int main()
{
Tuna tuna;
Carp carp;
DetectFishType(&tuna);
DetectFishType(&carp);
}
reinterpret_cast
- 能够让程序员能够将一种对象类型转换为另一种
应尽量避免在应用程序中使用reinterpret_cast,因为它让编译器将类型X视为不相关的类型Y,这看起来不像是优秀的设计或实现。
const_cast
- 让程序员能够关闭对象的访问修饰符const
使用场景:拿到一个const引用的对象,通过这个对象操作非const的成员函数,编译器会报错,为了解决这个错误,需要使用到const_cast解除对象的const访问修饰符
#include <iostream>
using namespace std;
class A
{
public:
void print()
{
cout << "A print" << endl;
}
};
void printAllData(const A& a)
{
A& ra = const_cast<A&>(a);
ra.print();
}
int main()
{
A a;
printAllData(a);
return 0;
}
网友评论