BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #35796同步于 2010/2/8
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

为啥说static_cast无法从*转换到char*啊

baoyu430
2010/2/8镜像同步6 回复
struct { int width; int height; } rectangle; 为啥说static_cast无法从*转换到char*啊? in_file.read(static_cast<char *>(&rectangle), sizeof(rectangle)); if (in_file.bad( )) { cerr << "Unable to read rectangle\n"; exit (8); } if (in_file.gcount( ) != sizeof(rectangle)) { cerr << "Error: Unable to read full rectangle\n"; cerr << "I/O error of EOF encountered\n"; } [em9] 书上的例子 为啥不能运行啊?*转换类型的时候 有什么限制或者要求吗?
订阅后,新回复会通过你的通知中心匿名送达。
6 条回复
ericyosho机器人#1 · 2010/2/8
reinterpret不行么?
jokerlee机器人#2 · 2010/2/8
【 在 baoyu430 的大作中提到: 】 : struct { : int width; : int height; : ................... static_cast 和 dynamic_cast都是用于继承链上对象指针的转换 请用reinterpret_cast 进行其他指针转换
bupteinstein机器人#3 · 2010/2/9
static_cast是什么意思来着?
ericyosho机器人#4 · 2010/2/9
static_cast是说,转换前和转换后的内容,有语义上的联系 比如 int i = 3; static_cast<double>(i); 得到的结果是 3.0 3 和 3.0在语义上是一致的.
coolwc机器人#5 · 2010/2/9
给你彻底分析一下吧 首先 struct的定义方式是这样的 struct <struct_name>{xxxxx} <instances> 而你定义的时候没有给出 struct_name 这样子的话 编译器只能给其赋予一个unname_xxx的临时名字 然后 由于static_cast是会经过编译器的严格检查的 而对于(unname_xxxxx*, char*)这样的一个转换自然无法通过检查 那么即使你赋予了一个名字 比如 struct RECT{} rectangle 这样依然通过不了检查 因为(RECT*, char*)这样的转换显然meaningless 对于这样的强制转换 1 使用 reinterpret_cast 2 使用c-style cast 至于dynamic_cast 是用在多态上的 主要是加入了运行期类型检查 也正是static_cast的反义词 【 在 baoyu430 (【团长尾随团】Alice9条~) 的大作中提到: 】 : struct { : int width; : int height; : ...................
josephbupt机器人#6 · 2010/2/9
直接这样不就行了么: in_file.read((char *)(&rectangle), sizeof(rectangle));