【问题标题】:Self-referential typedef without object or struct没有对象或结构的自引用 typedef
【发布时间】:2017-02-25 02:25:16
【问题描述】:

我对 c++ 还很陌生,我正在尝试使用 std::map 或其他 c++ 标准库容器类来实现一个简单的 trie 来存储字符串词典。我想做的是使用类似

typedef (map<char, type_node>)* type_node;

clang++ 给了我错误'使用未声明的标识符“type_node”'。

这与自引用结构相反,例如

typedef struct node {
   int data;
   struct node *next;
} Node;

不知何故,效果很好。

是否可以在不使用类或结构的情况下声明自引用类型?

为什么结构起作用而不是递归别名类型?

有没有更好的方法来做到这一点?

【问题讨论】:

  • 不。 typedef 是一个别名。别名不能前向声明。
  • 旁白:“面向对象”不是“使用类/结构”的同义词。
  • 不,基本上,类型系统需要有充分的基础。
  • 你不能在 typedef 中使用这样的括号

标签: c++


【解决方案1】:

您不能声明类型不完整的容器[1]。所以map&lt;char, type_node&gt; 是一个错误,因此别名也是一个错误。

在 C++ 中,所有结构都是隐式 typedef'd[2]。您的结构可以简化为:

struct node
{
   int data;
   node * next;
};

链接:

  1. Are C++ recursive type definitions possible, in particular can I put a vector<T> within the definition of T?

  2. Difference between 'struct' and 'typedef struct' in C++?

【讨论】:

  • struct node 的缺点是您没有自动添加映射工具。
  • struct node { map&lt;int, node*&gt; ptr;}怎么样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 2012-07-10
相关资源
最近更新 更多