在 Objective C 中创建链接列表
typedef struct {
NSString *activty;
NSString *place;
float latitude;
float longitude;
} event;
typedef struct {
event *thing;
Node *next;
} Node;
这是我在 .h 文件中创建两个结构来保存数据的代码(一个用于事件名称/地点/位置,另一个用于链接列表的节点。我可以在节点结构中使用事件结构,但我需要在 C++ 中使用节点结构,但我如何在 Objective-C 中实现这一点,谢谢!
typedef struct {
NSString *activty;
NSString *place;
float latitude;
float longitude;
} event;
typedef struct {
event *thing;
Node *next;
} Node;
This is the code I have in my .h file to create two structs to hold data (one for an events name/place/location, and one for the nodes of a linked list. I can use the event struct in the node struct, but I need to use the node struct within itself. In C++ this would work, but how can I achieve this in objective-c? Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么要为结构体操心呢?只需使用一个类:
与结构相比,没有显着的开销(如果方法调用确实可测量,您甚至可以直接公开 ivars)。更好的是,当您想要归档结构、添加业务逻辑或做任何其他有趣的事情时,您可以简单地添加方法。
Why bother with a struct? Just use a class:
There is no significant overhead vs. a structure (if the method calls are really measurable, you could even expose ivars directly). Better yet, the moment you want to archive the struct, add business logic, or do anything else interesting, you can simply add methods.
您需要像在 C 中那样命名您的结构。例如:
不过,一个更好的问题是,您为什么要首先创建这个链表?为什么不使用框架提供的容器类型之一?
You need to name your structure like you would in C. For example:
A better question, though, is why do you want to make this linked list in the first place? Why not use one of the container types provided by the framework?
我想你会发现它在 C++ 中不起作用(但他们可能改变了语法规则,以便它可以起作用)。您的意思可能更像是这样的:
这在 C++ 中有效,因为如果还没有名为
Node
的东西,则Node
相当于struct Node
(当 Foo 既是一个类又是另一个类的实例方法时,这有时会导致令人费解的错误,这种情况在某些编码风格中会发生)。修复方法是使用
struct Node
。我更喜欢这个;看起来更加纯粹。使用 typedef 有一些很好的理由(例如像TUInt64
这样的东西,由于缺乏编译器支持,它在历史上可能是一个结构体)。如果您确实使用 typedef,则没有理由为结构体指定不同的名称,因为它们位于不同的命名空间中(IIRC 结构体是“标记命名空间”)。通常的 typedef 版本是这样的:
或者,将文件扩展名更改为 .mm,然后它就可以工作,因为您正在编译 Objective-C++!
I think you'll find that it doesn't work in C++ (but they might have changed the grammar rules so that it does). You probably mean something more like this:
That works in C++ because
Node
is equivalent tostruct Node
if there isn't already something calledNode
(this sometimes causes puzzling errors whenFoo
is both a class and the instance method of another class, which happens in some coding styles).The fix is to say
struct Node
. I prefer this; it seems more pure. There are some good reasons to use a typedef (e.g. things likeTUInt64
which might have historically been a struct due to lack of compiler support). If you do use a typedef, there's no reason to give the struct a different name since they're in different namespaces (IIRC structs are a "tag namespace").The usual typedef version is something like this:
Alternatively, change the file extension to .mm and then it works because you're compiling Objective-C++!