无法理解 write() 的第一个参数

发布于 2024-11-17 23:02:22 字数 335 浏览 1 评论 0原文

我遇到了这样的说法:

outbal.write( (char*) &acc , sizeof( struct status ) );

outbalofstream 的对象,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

捎一片雪花 2024-11-24 23:02:22

(char*)&acc 如果是变量 acc 的地址,则强制转换为 char 指针,以便与 ostream::write()。正是该变量被写入 outbal 流,长度为 sizeof(struct status)

ostream::write 获取内存地址和长度,并将该内存输出到指定的流。换句话说,您只是输出 acc 变量的整个内存内容。

您的代码类似于:

struct xyz {int a; float b; void *c};

ostream os("myfile.dat");

struct xyz abc; // 'struct' not technically needed in C++

os.write (  (char *)abc,      sizeof (struct xyz));
//        <<-memory addr->>   <<-----size----->>

(char*)&acc if the address of the variable acc, cast to a char pointer so as to be compatible with ostream::write(). It is that variable that is being written, to the outbal stream, for a length of sizeof(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 the acc variable.

Your code is similar to:

struct xyz {int a; float b; void *c};

ostream os("myfile.dat");

struct xyz abc; // 'struct' not technically needed in C++

os.write (  (char *)abc,      sizeof (struct xyz));
//        <<-memory addr->>   <<-----size----->>
夜未央樱花落 2024-11-24 23:02:22

您将获取 acc 的地址并将其转换为 char*,这是 ostream::write 成员函数所期望的。

简而言之,您正在将结构体的内存表示形式按原样写入流。

You are taking the address of acc and casting it to char*, which is what the ostream::write member function expects.

In short, you are writing the in-memory representation of the struct as-is to a stream.

唠甜嗑 2024-11-24 23:02:22

(char*) &acc 获取 struct acc 的地址(即指向 acc 的指针),然后将其转换为指向一个字符

(char*) &acc takes the address of the struct acc (i.e. a pointer to acc) and then casts it into a pointer to a char.

坚持沉默 2024-11-24 23:02:22

这只是获取 acc 的地址并将其转换为指向 char 的指针。

最有可能的是 .write() 方法只是盲目地按原样写入给定数量的字节。 char 是一种方便的类型,因为(在大多数平台上)它的大小恰好是一个字节。因此,您将一个指向要写出的数据的指针传递给它,告诉它“假装这是一个指向 char”的指针。

That's just taking the address of acc and casting it to a pointer to char.

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 to char".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文