【问题标题】:How to implement two structs that can access each other?如何实现两个可以互相访问的结构?
【发布时间】:2013-04-19 02:25:10
【问题描述】:

我写的代码:

    struct A;
    struct B;
    struct A
    {
        int v;
        int f(B b)
        {
            return b.v;
        }
    };

    struct B
    {
        int v;
        int f(A a)
        {
            return a.v;
        }
    };

编译信息:

|In member function 'int A::f(B)':|
11|error: 'b' has incomplete type|
7|error: forward declaration of 'struct B'|
||=== Build finished: 2 errors, 0 warnings (0 minutes, 0 seconds) ===|

我知道为什么该代码不正确,但我不知道如何实现两个可以相互访问的结构。有什么优雅的方法吗?提前致谢。

【问题讨论】:

  • 我将其重新标记为 C++,因为它不是 C。

标签: c++ syntax struct dependencies forward-declaration


【解决方案1】:

如果要保持成员函数的签名完全相同,则必须推迟成员函数的定义,直到看到两个类定义

    // forward declarations
    struct A;
    struct B;

    struct A
    {
        int v;
        int f(B b); // works thanks to forward declaration
    };

    struct B
    {
        int v;
        int f(A a);
    };

    int A::f(B b) { return b.v; } // full class definition of B has been seen
    int B::f(A a) { return a.v; } // full class definition of A has been seen

您也可以使用const& 函数参数(当AB 很大时性能更好),但即使这样,您也必须推迟函数定义,直到看到两个类定义。

【讨论】:

  • 我只想指出像 const A &a 这样的东西存在。
  • 你是唯一一个声称不需要指针的人,我测试你的代码,工作!你是 C++ 专家!
  • @Vyktor tnx,我为此添加了一句话。
  • @Sayakiss 指针只有在你想要struct A { B* b; };struct B { A* a; }; 之类的东西时才需要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-09
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-24
  • 2014-12-24
相关资源
最近更新 更多