大佬教程收集整理的这篇文章主要介绍了C++强制类型转换运算符(static_cast、reinterpret_cast、const_cast和dynamic_cast),大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
_cast
字符串就可以了。甚至可以根据错误的类型,有针对性地专门查找某一种强制类型转换。例如,怀疑一个错误可能是由于使用了 reinterpret_cast 导致的,就可以只查找reinterpret_cast
字符串。强制类型转换运算符 <要转换到的类型> (待转换的表达式)
例如:double d = static_cast <double> (3*5); //将 3*5 的值转换成实数
下面分别介绍四种强制类型转换运算符。#include <iostream> using namespace std; class A { public: operator int() { return 1; } operator char*() { return NULL; } }; int main() { A a; int n; char* p = "New Dragon Inn"; n = static_cast <int> (3.14); // n 的值变为 3 n = static_cast <int> (a); //调用 a.operator int,n 的值变为 1 p = static_cast <char*> (a); //调用 a.operator char*,p 的值变为 NULL n = static_cast <int> (p); //编译错误,static_cast不能将指针转换成整型 p = static_cast <char*> (n); //编译错误,static_cast 不能将整型转换成指针 return 0; }
#include <iostream> using namespace std; class A { public: int i; int j; A(int n):i(n),j(n) { } }; int main() { A a(100); int &r = reinterpret_cast<int&>(a); //强行让 r 引用 a r = 200; //把 a.i 变成了 200 cout << a.i << "," << a.j << endl; // 输出 200,100 int n = 300; A *pa = reinterpret_cast<A*> ( & n); //强行让 pa 指向 n pa->i = 400; // n 变成 400 pa->j = 500; //此条语句不安全,很可能导致程序崩溃 cout << n << endl; // 输出 400 long long la = 0x12345678abcdLL; pa = reinterpret_cast<A*>(la); //la太长,只取低32位0x5678abcd拷贝给pa unsigned int u = reinterpret_cast<unsigned int>(pa);//pa逐个比特拷贝到u cout << hex << u << endl; //输出 5678abcd typedef void (* PF1) (int); typedef int (* PF2) (int,char *); PF1 pf1; PF2 pf2; pf2 = reinterpret_cast<PF2>(pf1); //两个不同类型的函数指针之间可以互相转换 }程序的输出结果是:
const String s = "Inception"; String& p = const_cast <String&> (s); String* ps = const_cast <String*> (&s); // &s 的类型是 const String*
#include <iostream> #include <String> using namespace std; class Base { //有虚函数,因此是多态基类 public: virtual ~Base() {} }; class Derived : public Base { }; int main() { Base b; Derived d; Derived* pd; pd = reinterpret_cast <Derived*> (&b); if (pd == NULL) //此处pd不会为 NULL。reinterpret_cast不检查安全性,总是进行转换 cout << "unsafe reinterpret_cast" << endl; //不会执行 pd = dynamic_cast <Derived*> (&b); if (pd == NULL) //结果会是NULL,因为 &b 不指向派生类对象,此转换不安全 cout << "unsafe dynamic_cast1" << endl; //会执行 pd = dynamic_cast <Derived*> (&d); //安全的转换 if (pd == NULL) //此处 pd 不会为 NULL cout << "unsafe dynamic_cast2" << endl; //不会执行 return 0; }程序的输出结果是:
Derived & r = dynamic_cast <Derived &> (b);
那该如何判断该转换是否安全呢?不存在空引用,因此不能通过返回值来判断转换是否安全。C++ 的解决办法是:dynamic_cast 在进行引用的强制转换时,如果发现转换不安全,就会拋出一个异常,通过处理异常,就能发现不安全的转换。以上是大佬教程为你收集整理的C++强制类型转换运算符(static_cast、reinterpret_cast、const_cast和dynamic_cast)全部内容,希望文章能够帮你解决C++强制类型转换运算符(static_cast、reinterpret_cast、const_cast和dynamic_cast)所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。