圆形类型定义

Circular Typedefs

本文关键字:定义 类型      更新时间:2023-10-16

此代码编译失败:

class B;
class A{
  typedef int AThing;
  typedef B::BThing BThing;
};
class B{
  typedef int BThing;
  typedef A::Athing AThing;
};

因为A需要Btypedef,而B需要A的。

使用具有循环依赖项的 typedef 的典型方法是什么?

具有此类循环typedef依赖项的典型解决方案是不要具有此类循环typedef依赖项。这些类型的循环typedef依赖关系无法在C++中完成,因此您必须重新排列类层次结构:

class B;
typedef int this_is_a_BThing;
class A{
  typedef int AThing;
  typedef this_is_a_Bthing BThing;
};
class B{
  typedef this_is_a_BThing BThing;
  typedef A::Athing AThing;
};

使用具有循环依赖项的 typedef 的典型方法是什么?

没有这种典型的方法,你不能那样做。

有关如何使用前向声明并在类型范围内扩展依赖类型定义的情况,请参阅 Resolve 标头中的答案包括C++中的循环依赖项。

您在类范围内引入typedef的情况与编译器无法通过查看前向声明来解决它这一事实无关紧要。


我能想到使用 typedefs 的唯一方法是使用 Pimpl Idion 并仅在实现中实际引入它们。