c++ - 如何实现两个可以相互访问的结构体?

标签 c++ syntax struct dependencies forward-declaration

我写的代码:

    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) ===|

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

最佳答案

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

    // 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 较大时性能更好),但即使那样您也必须推迟函数定义,直到看到两个类定义。

关于c++ - 如何实现两个可以相互访问的结构体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16210569/

相关文章:

c++ - 结构奇怪的偏移

将数据从 struct net_device_stats 复制到用户空间

C++ 通过引用传递不改变值

c++ - 静态多态中纯抽象函数的等价物是什么?

尝试呈现 SDL_Texture : Invalid texture 时出现 C++ SDL2 错误

gcc - ARM-GCC 的 ISR 语法

php - OpenCart中MySQL查询代码语法错误

c++ - 如何用 C++11 中的 lambda 调用替换仿函数调用?

c 程序 openmp 的多个语法错误

ios - 使用 UISearchController 搜索后编辑过滤数组的最佳方法