小门户网站模版,wordpress发布文章404,黄山网站建设黄山,网站用什么cms文章目录1.dynamic_cast2.const_cast3.3 static_cast3.4 reinterpret_cast1.dynamic_cast 用于动态类型转换。只能用于含有虚函数的类#xff0c;用于类层次间的向上和向下转化。只能转指针或引用。向下转化时#xff0c;如果是非法的对于指针返回NULL#xff0c;对于引用抛…
文章目录1.dynamic_cast2.const_cast3.3 static_cast3.4 reinterpret_cast1.dynamic_cast 用于动态类型转换。只能用于含有虚函数的类用于类层次间的向上和向下转化。只能转指针或引用。向下转化时如果是非法的对于指针返回NULL对于引用抛异常。要深入了解内部转换的原理。 向上转换指的是子类向基类的转换 向下转换指的是基类向子类的转换 它通过判断在执行到该语句的时候变量的运行时类型和要转换的类型是否相同来判断是否能够进行向下转换。 #includeiostream
#includestack
#includestring
#includevector
#includeset
using namespace std;class A {
public:virtual void print() {cout A base endl;}
};
class B :public A {
public:virtual void print() {cout B derived endl;}
};
int main()
{/*1.dynamic_cast的向上转换子类向父类指针的转化即ptr_b —— ptr_a这也是实现虚函数的基础虚函数的子类父类之间的向上转换总是安全的*/B* ptr_b1new B;A* ptr_a1 dynamic_castA*(ptr_b1);/*B* ptr_bnew B;A* ptr_aptr_b;*//*A* ptr_anew B;*/ptr_a1-print();/*2.dynamic_cast的向下转换父类指针向子类指针的转换向下转换可能不安全*/A* ptr_a2 new A;B* ptr_b2 dynamic_castB*(ptr_a2);if (ptr_b2) {cout ptr_a2向ptr_b2转换成功 endl;ptr_b2-print();}else {cout ptr_b2为null,ptr_a2向ptr_b2转换失败 endl;}A* ptr_a3 new B;//这是向下转换成功的关键B* ptr_b3 dynamic_castB*(ptr_a3);if (ptr_b3) {cout ptr_a3向ptr_b3转换成功 endl;ptr_b3-print();}else {cout ptr_b3为null,ptr_a3向ptr_b3转换失败 endl;}return 0;
}B derived
ptr_b2为null,ptr_a2向ptr_b2转换失败
ptr_a3向ptr_b3转换成功
B derived2.const_cast 用于将const变量转为非const 但需要特别注意的是const_cast不是用于去除变量的常量性而是去除指向常数对象的指针或引用的常量性其去除常量性的对象必须为指针或引用。 #includeiostream
#includestack
#includestring
#includevector
#includeset
using namespace std;int main()
{const int A 4;const int* ptr1 A;int* ptr2 const_castint*(ptr1);//*ptr2 44;如果直接如此则错误cout A A endl;cout *ptr1 *ptr1 endl;cout *ptr2 *ptr2 endl;return 0;
}3.3 static_cast 用于各种隐式转换比如非const转constvoid*转指针等, static_cast能用于多态向上转化如果向下转能成功但是不安全结果未知 3.4 reinterpret_cast 几乎什么都可以转比如将int转指针可能会出问题尽量少用 为什么不使用C的强制转换 C的强制转换表面上看起来功能强大什么都能转但是转化不够明确不能进行错误检查容易出错。