11:17:57 例: static-cast void func (int) void main o int i=0x7fff. long 1: float f =i: f=i //更好的方法是使用 static_cas t 1=static-cast<long>(i); f=static-cast<float>(i) i=1:i=f /以上两条语句会出 Warning,可使用如下方式消除 i=static-cast<int>(1; i=static-cast<int>(f) char c=static-cast<int>(i) void *vp=&f float *fp=(float*)vp //C的方法,不好 fp= static-cast< float*>(vp);//更好的方法 double d=0. 0: int x=d /自动发生隐式类型转换 x=(int)d: //C的方法,不好 X=Static-cast<int> //更好的方法 func(d) /自动发生隐式类型转换 func(static-cast<int>(d)) 更好的方法
11:17:5711 例:static_cast void func(int){ } void main() { int i=0x7fff; long l; float f; l=i;f=i; //更好的方法是使用static_cast l=static_cast<long>(i); f=static_cast<float>(i); i=l;i=f; //以上两条语句会出Warning,可使用如下方式消除 i=static_cast<int>(l); i=static_cast<int>(f); char c=static_cast<int>(i); void *vp=&f; float *fp=(float*)vp; //C的方法,不好 fp=static_cast<float*>(vp); //更好的方法 double d=0.0; int x=d; //自动发生隐式类型转换 x=(int)d; //C的方法,不好 x=static_cast<int>(d); //更好的方法 func(d); //自动发生隐式类型转换 func(static_cast<int>(d)); //更好的方法 }
11:17:57 例: const-cast void main o const int i=0 //int*j=&i;/错误,不允许这样赋值 int*k=(int*)&i;∥被弃的方法 k=const-cast<int*>(&1) //long*1=const-cast<long*>( &1) 错误,不允许同时进行c0nt*一> nonConst* /和0 nCos t*-)10ng*两项转换
11:17:5712 例:const_cast void main() { const int i=0; //int *j=&i; //错误,不允许这样赋值 int *k=(int*)&i; //被摒弃的方法 k=const_cast<int*>(&i); //long *l=const_cast<long*>(&i); //错误,不允许同时进行const*->nonConst* //和nonConst*->long*两项转换 }
11:17:57 例: reinterpret-cast #include <iostream> using names pace stds const int sz=100: struct X int a [sz] void print(X* x) for (int i=0: i<sz: i++ cout<<x->a[i]<<""; cout < end1 < I<< end1 void ma in O XX print(&x) int *xp=reinterpret-cast<int*>(&x) for (int *i=xp; i<xp+sz; i++) *1=10 print (reinterpret-cast<X*>(xp)) print (&x);
11:17:5713 例:reinterpret_cast #include <iostream> using namespace std ; const int sz=100; struct X {int a[sz];}; void print( X* x) { for (int i=0;i<sz;i++) cout << x ->a[i] << " "; cout << endl << "-----------------" << endl; } void main() { X x; print(&x); int *xp=reinterpret_cast <int*>(&x); for (int *i=xp;i<xp+sz;i++) *i=10; print (reinterpret_cast<X*>(xp)); print(&x); }
11:17:57 2.表达式 由运算符连接操作数构成的式子 算术表达式 关系表达式 逻辑表达式 赋值表达式 条件表达式 逗号表达式
11:17:5714 2.表达式 由运算符连接操作数构成的式子 – 算术表达式 – 关系表达式 – 逻辑表达式 – 赋值表达式 – 条件表达式 – 逗号表达式
11:17:57 §3常量与变量 C++中的常量 1.直接常量(字面常量):10,10.5,A,“ string” int型.f1oat型char型字符串常量 b001型:true、fale 2.符号常量:C+中有两种符号常量 # define定义的常量 例:# efine pi3.1415926 关键字 const定义的常量 例: const int sz=100: # define定义的常量,在预处理时只是字符串的替换, 对编译器而言,不带有任何类型信息,不便于查错;而 cons t定义的常量带有类型信息,故优于# define定义的 常量 C+-推荐使用 cons t定义的常量 15
11:17:5715 §3 常量与变量 一.C++中的常量 1.直接常量(字面常量): 10,10.5, ‘A’ , “string” .int型 .float型 .char型 .字符串常量 .bool型:true、false 2.符号常量:C++中有两种符号常量 – #define定义的常量 例:#define pi 3.1415926 – 关键字const定义的常量 例:const int sz=100; – #define定义的常量,在预处理时只是字符串的替换, 对编译器而言,不带有任何类型信息,不便于查错;而 const定义的常量带有类型信息,故优于#define定义的 常量 – C++推荐使用const定义的常量