gpt4 book ai didi

c - 一个简单的对象系统

转载 作者:行者123 更新时间:2023-12-01 12:42:38 25 4
gpt4 key购买 nike

我正在学习 learn c the hard way 这本书,在练习 19 中遇到了一些问题。作者说 ex19 旨在让学习者了解 c 中的宏。我在理解这个概念上没有问题,但我就是不明白其他的一切。我无法理解对象原型(prototype)是如何创建的。

特别是,下面的句子是什么意思?

Since C puts the Room.proto field first, that means the el pointer is really only pointing at enough of the block of memory to see a full Object struct. It has no idea that it's even called proto.

相关代码是这样的:

// this seems weird, but we can make a struct of one size,
// then point a different pointer at it to "cast" it
Object *el = calloc(1, size);
*el = proto;
  1. 谁能告诉我 malloc/calloc 究竟是如何工作的?据我所知,它只是分配所需数量的内存并返回第一个地址。如果是这样,计算机如何知道分配内存的数据结构?就像在代码中一样,在 Room *arena = NEW(Room, "The arena, with the minotaur"); 之后,你可以直接这样做 arena->bad_guy = NEW(Monster, "The evil minotaur"); 计算机怎么知道有一个bad_guy??
  2. 上面两条语句(Object *el = calloc(1, size); and *el = proto;)后*el的内容到底是什么?

任何帮助将不胜感激!!

练习链接:http://c.learncodethehardway.org/book/ex19.html

最佳答案

calloc 具有附加功能,它用零字节填充分配的内存,而使用等效的 malloc 调用将需要一个额外的步骤,如果全部或部分分配最初需要为零。

在代码中

arena->bad_guy = NEW(Monster, "The evil minotaur"); 

编译器知道结构的布局,因为访问是通过 arena 变量进行的,该变量被声明为指向 Room 的指针,它可能是结构的 typedef

另一方面,结构内的顺序保证允许在复合结构或扩展结构中进行有限形式的继承

struct A {
int x;
};

struct B {
int foo;
double baloney;
};

struct B(或指向它的指针)可以转换为(指向 a 的指针)struct A,因为它们都以 int 。当然,如果你用另一种方式转换,struct A 本来就是一个 struct B 否则访问 baloney 字段将是未定义的.换句话说,struct B 本质上以 struct A 开头。

如果我像这样重写我的示例,这可能更容易看到:

struct A {
int x;
};

struct B {
struct A foo;
double baloney;
};

现在你可以用不同的方式从 struct B 中得到一个 struct A

struct A a;
struct B b;

a = b.foo; // regular member variable access

struct A *ap = &a;
struct B *bp = &b;

ap = (struct A *)bp; // cast the pointer

ap = & b.foo; // take a pointer from the member variable
ap = & bp->foo; // take a pointer from the member variable via a pointer

关于c - 一个简单的对象系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22782310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com