static_cast 静态转换
dynamic_cast 动态转换
const_cast 去常性
reinterpret_cast 重新解释
一、static_cast
static_cast<目的类型>(表达式)
1.基本数据类型之间的转换
2.枚举类型之间的转换
3.指针类型转换成void*
4.将一个变量转换成常量
5.static_cast不能移除变量的const属性
6.基类和派生类之间的转换--
7.没有关系的类之间的转换
class A
{
public:
void fn() { cout << "A::fn" << endl; }
};
class B
{
public:
B(A& a) {}
void gn() { cout << "B::gn" << endl; }
};
void main()
{
A a;
B b =static_cast<B>(a); //B b(a)
b.gn();
}
class A
{
public:
void fn() { cout << "A::fn" << endl; }
void gn() { cout << "A::gn" << endl; }
};
class B :public A
{
public:
void fn() { cout << "B::fn" << endl; }
void hn() { cout << "B::hn" << endl; }
};
void main()
{
A a;
B b;
A* pa = &b;
pa->fn();
pa->gn();
B* pb = static_cast<B*>(&a);
pb->A::fn();
pb->fn();
pb->gn();
pb->hn();
}
void main()
{
const int cb = 20;
//int* p = static_cast<int*>(&cb);
int* p = const_cast<int*>(&cb);
*p = 50;
cout << cb << endl;
}
#if 0
void main()
{
//int a = 20;
//const int ca = static_cast<const int>(a);
//cout << ca << endl;
}
#endif
#if 0
void main()
{
int a = 10;
int* p = nullptr;
char ch = 'a';
void* vp = &a;
p = static_cast<int*>(vp); //ok
cout << *p << endl;
vp = &ch;
p = static_cast<int*>(vp); //不安全
cout << *p << endl;
}
#endif
#if 0
void main()
{
//enum weekend {}
enum AA { A = 3, B = 10 };
enum BB { C = 5, D = 20 };
int a = 10;
enum AA aa = B;
cout << aa << endl;
aa = static_cast<enum AA>(a);
cout << aa << endl;
enum BB bb = C;
aa =static_cast<enum AA> (bb);
cout << aa << endl;
}
#endif
#if 0
void main()
{
int a = 5;
float b = 45.7;
/* printf("%f\n", (float)a);
printf("%d\n", (int)b);*/
a = static_cast<int>(b);
char c = 'c';
a = static_cast<int>(c);
}
#endif
二、dynamic_cast
--将基类的指针或引用安全的转换成派生类的指针或引用,并用派生类的指针
或者引用来调用非虚函数
注意:当使用dynamic_cast时,该类型要包含有虚函数,才能进行转换,否则错误文章来源:https://www.toymoban.com/news/detail-467494.html
class A
{
public:
void print() { cout << "A::print" << endl; }
virtual ~A() {}
};
class B :public A
{
public:
void show() { cout << "B::show" << endl; }
};
void main()
{
A* pa = new A;
B* pb = dynamic_cast<B*>(pa);
pb->print();
pb->show();
}
三、reinterpret_cast适用于指针转换为另一种指针,转换不用修改指针变量值数据存储格式
(不改变指针变量值),只需要在编译时重新解释指针的类型即可
当然也可以将指针转换成整型值文章来源地址https://www.toymoban.com/news/detail-467494.html
#if 0
void main()
{
float ff = 3.5f;
float* pf = &ff;
int* pi = reinterpret_cast<int*>(pf);
cout << *pi << endl; //取不到正确的值
cout << *pf << endl;
// unsigned int a = -2;
// printf("%u %d\n", a, a);
}
#endif
#if 0
class A
{
};
class B
{
};
void main()
{
A* pa = new A;
B* pb = reinterpret_cast<B*>(pa);
//B *pb = (B*)pa
int a = 10;
int* pi = &a;
long j = reinterpret_cast<long>(pi);
cout << j << endl; //地址值
}
到了这里,关于4个强制类型转换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!