【问题标题】:How to use 'struct' prototypes in C++? [duplicate]如何在 C++ 中使用“结构”原型? [复制]
【发布时间】:2020-12-01 05:45:47
【问题描述】:

假设有 3 个函数 f1,f2,f3

它们以循环方式使用。 f1 需要 f2 f2 需要 f3 f3 需要 f1

所以,在编写代码时,我们必须使用函数原型来避免错误。

但是结构呢? 我们如何使用结构来做到这一点,因为 C++ 中不允许使用结构原型

【问题讨论】:

  • 我认为您可能正在寻找前瞻性声明。这是您所谓的原型的实际名称。您实际上不能让 f1 包含一个 f2 包含一个 f3 包含一个 f1 因为 f1 将包含一个 f2 将包含一个 f3 将包含一个 f1 将包含一个 f2 将包含一个 f3 将包含一个 f1 会包含一个 f2 将包含一个 f3 将包含一个 f1 将包含一个 f2 将包含一个 f3 将包含一个 f1 将包含一个 f2 将包含一个 f3 将包含一个 f1...看到问题了吗?跨度>
  • 好的,我明白了!

标签: c++ struct function-prototypes


【解决方案1】:

至少其中一个结构只能通过指针或引用来引用另一个结构,并且必须像下面这样声明结构(无意义的代码,只是演示):

struct struct1;
struct struct2
{
  struct1 * ptr;
  size_t count;
};

struct struct1
{
  void foo(struct2 s2) { /* */ }
};

也可以使用详细的声明器来执行此操作,但这是不寻常的:

struct struct3
{
  struct struct4 * ptr;
  size_t count;
};

struct struct4
{
  void foo(struct3 st3) { /* */ }
};

【讨论】:

    【解决方案2】:

    所谓的“结构原型”称为前向声明。例如:

    struct A; //forward declaration of A
    
    struct B 
    { 
       A* a;
    }; //definition of B
    
    struct A 
    {
       B b; /*need definition of B prior to this point*/
    }; //definition of A
    

    前向声明后,您只能使用指针或对结构的引用。您需要结构的定义才能将其用作成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      • 2013-08-20
      • 2021-04-23
      相关资源
      最近更新 更多