类型转换
隐式类型转换
char c = 'A' ;
int i = c;
-- -- -- -- -- -- -
void func ( int i) { . . }
func ( c) ;
-- -- -- -- -- -- -
int func ( void ) {
char c = 'A' ;
return c;
}
显式类型转换
C++兼容C中的强制类型转换
char c = 'A' ;
int i = ( int ) c;
int i = int ( c) ;
增加了四种操作符形式显式转换
静态类型转换
语法形式: 目标类型变量 = static_cast<目标类型>(源类型变量); 使用场景:
int a= 100 ;
void * pv = & a;
int * pi = static_cast < int * > ( pv) ;
动态类型转换 dynamic_cast - 运行时类型检查。可以父子之间转换,也可以兄弟之间转换。优点是安全,缺点是运行时效率低。 常类型转换
语法形式: 目标类型变量 = const_cast<目标类型>(源类型变量); 使用场景: 用于去除一个指针或引用的常属性 重解释类型转换
语法形式: 目标类型变量 = reinterpret_cast<目标类型>(源类型变量); 使用场景: –》任意类型指针或引用之间转换 –》在指针和整型数之间转换 eg:向物理内存0x12345678存放数据123?
int * paddr = reinterpret_cast < int * > ( 0x12345678 ) ;
* paddr = 123 ;
小结(C++之父给C程序员建议)
慎用宏,使用const、inline、enum替换
#define PAI 3.14
-- > const double PAI = 3.14 ;
#define max(a,b) ((a)>(b) ? (a):(b))
-- > inline int max ( int a, int b) {
return a> b ? a: b;
}
#define STATE_SLEEP 0
#define STATE_RUN 1
#define STATE_STOP 2
-- > enum STATE{ SLEEP, RUN, STOP} ;
变量随用随声明同时初始化 尽量使用new/delete替换malloc/free 少用void*、指针计算、联合体和强制转换 尽量使用string表示字符串,少用C风格char*
代码示例
#include <iostream>
using namespace std;
int main ( void )
{
int * pi = NULL ;
char c = long ( pi) ;
void * pv = pi;
pi = static_cast < int * > ( pv) ;
c = static_cast < long > ( pi) ;
return 0 ;
}
执行结果 const_cast.cpp
#include <iostream>
using namespace std;
int main ( void )
{
const volatile int ci = 10 ;
int * pci = const_cast < int * > ( & ci) ;
* pci = 20 ;
cout << "ci=" << ci << endl;
cout << "*pci=" << * pci << endl;
cout << "&ci=" << ( void * ) & ci << endl;
cout << "pci=" << pci << endl;
return 0 ;
}
执行结果 reinterpret_cast.cpp
#include <iostream>
using namespace std;
int main ( void )
{
char buf[ ] =
"0001\00012345678\000123456" ;
struct T{
char type[ 5 ] ;
char id[ 9 ] ;
char passwd[ 7 ] ;
} ;
T* pt = reinterpret_cast < T* > ( buf) ;
cout << pt- > type << endl;
cout << pt- > id << endl;
cout << pt- > passwd << endl;
return 0 ;
}
执行结果