标签:c++ 强制转换 static_cast
(一)隐式转换先来看一组样例:
int ival=0; ival=3.451+3;首先做加法操作,操作数分别为int和double类型,c++并没有直接把两个数加在一起,而是提供了一组转换规则,以便在执行算术操作之前,将两个操作数转换为同一种数据类型。在这里是自动执行的,所以他们被成为隐式转换。
int ival=0; double dval; ival>=dval;②用作条件的表达式转换成bool类型
int val; if(val) while(val)③ 用一个表达式初始化某个变量,或将一个表达式赋值给某个变量,则该表达式被转换成变量类型。
int ival=3.21; int *ip; ip=0; // the int converted to a null pointer of type int *3.由标准库类型定义的转换
string s; while(cin>>s)这里隐式使用了IO标准库定义的类型转换,返回的是cin,此处将istream类型的值转换为bool类型,意味这要检验流的状态,如果读取成功,返回true,如果失败,比如说读取到文件的末尾,那么转换为bool后为false;循环条件不成立。
double d =5.6; void* p=&d; double *dp=static_cast<double*>(*p);②const_cast
const char *pc; char *p =const_cast<char*>(pc); const int a=6; int &b=const_cast<int&>(a); int c=const_cast<int>(a); //error,具体对象之间是错误的③reiterpret_cast
int *ip; char *pc=reinterpret_cast<char*>(ip); //pc真实指向int型 string str(pc);// error ,int cannnot init string double a=8.97; double *p=&a; int b=reinterpret_cast<int>(p); cout<<b<<endl;错误的使用reinterpret_cast很容易导致程序的不安全,只有将转换后的类型值转换回到其原始类型,这样才是正确使用reinterpret_cast方式。不过,还是要谨慎的使用reinterpret_cast。
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
class A
{
int a;
virtual void p(){} //must
};
class B :public A
{
int b;
};
int main()
{
B nameB; A nameA;
A *p1=&nameA;
A* p = &nameB;
B* cur = dynamic_cast<B*>(p); // OK p point to B
B* cur1 = dynamic_cast<B*>(p1); // error,NULL,p1没有指向B
//cout << cur << endl;
try
{
A &k = nameA;
B &temp = dynamic_cast<B&>(k);
}
catch(bad_cast) {
cout << "bad_cast" << endl;
}
}(三)旧式强制转换int ival;double dval; ival+=int(dval); // static_cast :converts double to int const char* pc_str; string_copy((char*)pc_str);// const_cast casts away const int *ip; char*pc=(char*)p; //reinterpret_cast :treats int* as char*
版权声明:本文为博主原创文章,未经博主允许不得转载。
C++ Primer 学习笔记与思考_10 类型转换易错处大总结
标签:c++ 强制转换 static_cast
原文地址:http://blog.csdn.net/nk_test/article/details/48130891