您的位置:首页 > 编程语言 > C语言/C++

《C++深度剖析》学习日志八——数据类型转换

2018-02-07 22:29 225 查看
在C语言中的数据类型转换过于粗暴,我们先来分析下面一段C语言类型转换问题代码
#include <stdio.h>

typedef void(PF)(int);//定义了一个PF(int)函数

struct Point
{
int x;
int y;
};

int main()
{
int v = 0x12345;
PF* pf = (PF*)v;//函数的入口地址指向v的地址,这是不对的
char c = char(v);//强制将int转换为char,发生截断
Point* p = (Point*)v;//p指向Point结构体

pf(5);

printf("p->x = %d\n", p->x);
printf("p->y = %d\n", p->y);

return 0;
}
最后运行结果为:



在地址指向的地方错误,在大量代码下,查错是非常困难的,这样,就衍生出了C++的类型转换。
C方式类型转换的问题
 1.过于粗暴(任意类型都可以转换)
 2.难于定位



可以通过Find定位



基本类型包括int,char等。







强制类型转换是bug 的重要来源,一定要记住这四个关键字。
#include <stdio.h>

void static_cast_demo()
{
int i = 0x12345;
char c = 'c';
int* pi = &i;
char* pc = &c;

c = static_cast<char>(i);//R
pc = static_cast<char*>(pi);//E,因为static_cast不能用于指针间的转换
}

void const_cast_demo()
{
const int& j = 1;
int& k = const_cast<int&>(j);//去掉j的只读属性

const int x = 2;//进入了符号表
int& y = const_cast<int&>(x);//常量的只读属性是去不掉的,但是编译器还是执行了,意思是将x的内存空间地址给y

int z = const_cast<int>(x);//E,只能用于引用或指针之间

k = 5;

printf("k = %d\n", k);
printf("j = %d\n", j);

y = 8;

printf("x = %d\n", x);
printf("y = %d\n", y);
printf("&x = %p\n", &x);
printf("&y = %p\n", &y);
}

void reinterpret_cast_demo()
{
int i = 0;
char c = 'c';
int* pi = &i;
char* pc = &c;

pc = reinterpret_cast<char*>(pi);
pi = reinterpret_cast<int*>(pc);
pi = reinterpret_cast<int*>(i);//R,可以在整形和指针之间做转换
c = reinterpret_cast<char>(i); //E,不可以在基本类型间做转换
}

void dynamic_cast_demo()
{
int i = 0;
int* pi = &i;
char* pc = dynamic_cast<char*>(pi);//E,要有类和虚函数
}

int main()
{
static_cast_demo();
const_cast_demo();
reinterpret_cast_demo();
dynamic_cast_demo();

return 0;
}
要记住这些规则,这些规则能很好的改善C语言中存在的类型间强制转换的问题,并且提高查错能力。

以上资料均来自狄泰,群号:199546072,志同道合的朋友可以加我:
 qq:335366243
 微信:zhong_335366243
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: