【问题标题】:Objective C - Using typedef struct in header fileObjective C - 在头文件中使用 typedef 结构
【发布时间】:2014-02-16 09:25:25
【问题描述】:

我正在尝试在 Objective C 中创建一个 LinkedList。

在 .h 文件中,我尝试使用代码创建节点:

@interface AALinkedList : NSObject
{
    typedef struct Node
    {
        int data;
        struct Node *next;
    } Node;
}

这给了我一个错误说Type name does not allow storage class to be specified

这是什么意思?以及如何解决?

【问题讨论】:

  • 您不能在 Objective-C 类的数据部分定义新类型。 storage class 是关于typedef,因为它是一个存储类,就像staticauto 一样。

标签: objective-c c linked-list


【解决方案1】:
typedef struct Node {
    int data;
    Node *next;
} Node;

@interface AALinkedList : NSObject
{
    Node node;
    // or Node *node;
}

【讨论】:

  • 为什么会出现在@interface之上?
  • 因为@interface {struct { 几乎相同,并且您没有在结构体中定义新类型。即使你能做到,这也毫无意义,因为名称的范围将仅限于该结构。
【解决方案2】:

您不能在 .h 文件中声明 typedef。在 .m 中声明它。那应该可以让您继续前进。将方法签名放在 .h

你可以像这样创建一个简单的 LinkedList 类。

@interface LinkedNode : NSObject 
  @property (nonatomic, strong) id nextNode;
@end
then you use it as you would expect:

id currentNode = myFirstNode;
do {
  [currentNode someMessage];
}
while(currentNode = currentNode.nextNode);

【讨论】:

  • 为什么? .m 文件在哪里?
  • 这不是真的,您可以在 .h 或 .m 文件中在正确的位置声明它。不过,使用属性比结构更好。
猜你喜欢
  • 2013-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-02
  • 2022-08-11
相关资源
最近更新 更多