C++学习总结10--类型转换

小记:静默如初,安之若素

类型转换

1. 隐式类型转换

eg:
  char c = 'a';
  int i = c;//隐式转换(char->int->=)
  void func(int i){...}
  func(c);
   
  int foo(void)
  {
  	char c = 'a';
  	return c;
  }

2. 显示转换
2.1 C++兼容C的强制类型转换

eg:
	char c = 'a';
	int i = (int)c;//C风格
	int i = int(c);//C++风格

2.2 C++中增加了四种操作符形式的类型转换
1)静态类型转换
语法形式:
目标类型变量 = static_cast<目标类型>( 源类型变量);
适用场景:
将void*转为其它类型指针。

2)动态类型转换
语法形式:
目标类型变量 = dynamic_cast<目标类型>( 源类型变量);

3)常类型转换
语法形式:
目标类型变量 = const_cast<目标类型>( 源类型变量);
适用场景:
用于去除一个指针或引用的常属性;
void func(const int & a){…}

eg:
	const int a = 0;
	const int *pa = &a;
	*pa = 200;//error
	int *pa2 = const_cast<int*>(&a);
	*pa2 = 200;//ok
  1 #include <iostream>
  2 using namespace std;
  3 
  4 int main(int argc, char *argv[])
  5 {
  6   //volatile 修饰的变量表示是易变的,告诉编译器每次
  7   //再适用该变量都要从内存中重新加载而不是取寄存器中的副本,
  8   //防止因为编译器优化引发的错误结果。
  9   //const int ci = 100; 
 10   const volatile int ci = 100;
 11   //int *pci = &ci;//error.内存安全角度考虑
 12   int *pci = const_cast<int *>(&ci);//ok
 13   *pci = 200;
 14   cout <<"&ci = "<<(void*) &ci <<endl;//cout输出地址只能输出void*类型的
 15   cout <<"pci = "<< pci <<endl;
 16   cout <<"ci = "<< ci <<endl;//100, 加volatile后结果是200
 17   cout <<"*pci = "<< *pci <<endl;//200
 18   
 19   return 0;
 20 }

4)重解释类型转换
语法形式:
目标类型变量 = reinterpret_cast<目标类型>( 源类型变量);
适用场景:
1. 任意类型指针或引用之间转换;
2. 在指针和整形数之间进行转换;

eg:向物理内存0x12345678存放数据100int * paddr = reinterpret_cast<int*>(0x12345678);
*paddr = 100;
  1 #include<iostream>
  2 using namespace std;
  3 
  4 int main(void)
  5 {
  6   struct T{
  7     char type[5];
  8     char id[9];
  9     char passwd[7];
 10   };
 11   
 12   //"\000"<=> '\0' <=> 0
 13   char buf[] = "0001\00012345678\000123456";
 14   //T * pt = buf;//error
 15   T * pt = reinterpret_cast<T*>(buf);
 16   cout <<"type   : "<< pt->type << endl;//0001
 17   cout <<"id     : "<< pt->id << endl;//12345678
 18   cout <<"passwd : "<< pt->passwd << endl;
 19   return 0;
 20 }
 21 
运行结果
type   : 0001
id     : 12345678
passwd : 123456

小结:C++之父给C程序员的建议
1 慎用宏(#define),使用const,enum,inline替换;

eg:
	#define PAI 3.14 
     	==> const double PAI = 3.14
    ------------------------------
    #define STATE_SLEEP 0
    #define STATE_RUN   1
    #define STATE_STOP  2
        ==> enum STATE{SLEEP, RUN, STOP};
    #define max(a, b) ((a)>(b)?(a):(b))
        ==>inline int max(int a, int b){
        	  return a > b ? a : b;
            }

2 变量随用随声明同时初始化;

eg:
   char buff[1024];//未初始化,可能会造成部分内存未使用

3 尽量适用new / delete 替换 malloc / free;

4 少用void *, 指针计算, 联合体, 强制转换;

5 尽量使用string表示字符串,少用C风格char *。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值