无法理解 write() 的第一个参数
我遇到了这样的说法:
outbal.write( (char*) &acc , sizeof( struct status ) );
outbal
是 ofstream
的对象,status
是一种类型。
因此:
struct status {
// code
};
status acc;
谈论第二行我不理解第一个参数,即 (char*) &acc
。我们在做什么以及如何做?
I came across the statement:
outbal.write( (char*) &acc , sizeof( struct status ) );
outbal
is an object of ofstream
and status
is a type.
Therefore:
struct status {
// code
};
status acc;
Talking about the second line I don't understand the first argument, which is (char*) &acc
. What are we doing and how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
(char*)&acc
如果是变量acc
的地址,则强制转换为 char 指针,以便与ostream::write()
。正是该变量被写入outbal
流,长度为sizeof(struct status)
。ostream::write
获取内存地址和长度,并将该内存输出到指定的流。换句话说,您只是输出acc
变量的整个内存内容。您的代码类似于:
(char*)&acc
if the address of the variableacc
, cast to a char pointer so as to be compatible withostream::write()
. It is that variable that is being written, to theoutbal
stream, for a length ofsizeof(struct status)
.ostream::write
takes a memory address and a length and will output that memory to the specified stream. In other words, you're simply outputting the entire memory contents of theacc
variable.Your code is similar to:
您将获取
acc
的地址并将其转换为char*
,这是ostream::write
成员函数所期望的。简而言之,您正在将结构体的内存表示形式按原样写入流。
You are taking the address of
acc
and casting it tochar*
, which is what theostream::write
member function expects.In short, you are writing the in-memory representation of the struct as-is to a stream.
(char*) &acc
获取 structacc
的地址(即指向acc
的指针),然后将其转换为指向一个字符
。(char*) &acc
takes the address of the structacc
(i.e. a pointer toacc
) and then casts it into a pointer to achar
.这只是获取 acc 的地址并将其转换为指向 char 的指针。
最有可能的是
.write()
方法只是盲目地按原样写入给定数量的字节。char
是一种方便的类型,因为(在大多数平台上)它的大小恰好是一个字节。因此,您将一个指向要写出的数据的指针传递给它,告诉它“假装这是一个指向char
”的指针。That's just taking the address of
acc
and casting it to a pointer tochar
.Most likely that
.write()
method is meant to just blindly write a given amount of bytes out as-is.char
is a convienent type to use for that, since (on most platforms) it is exactly one byte in size. So you pass it a pointer to the data you want written out, telling it, "Pretend this is a pointer tochar
".