首页 > 解决方案 > 我可以存储指向转发声明的类/结构的指针吗?

问题描述

#include <stdio.h>

struct B;
struct A {
    B* b;
    int num = 4;
    
    A() {
        b = new B(this);
    }
};

struct A;
struct B {
    A* a;
    int num = 21;
    
    B(A* a) {
        this->a = a;
    }
    
    // function that does stuff with both A and B nums
    int add() {
        return num + a->num;
    }
};

int main()
{
    A thing;
    printf("%d",thing.b->add());
    return 0;
}

所以我的代码中有两个结构,其中 structB是 struct 的成员A。我只是希望他们存储彼此的指针,以便他们可以访问彼此的成员变量。这甚至可能吗?我愿意接受重构建议。

标签: c++

解决方案


这是可能的,但您将不得不移动一些代码,因为在完全知道类型之前无法编译许多表达式。例如,在完全知道new B(this)之前无法编译。B

所以A构造函数需要在B定义后编译,像这样

struct B;

struct A {
    B* b;
    int num = 4;
    
    A();
};

struct B {
    A* a;
    int num = 21;
    
    B(A* a) {
        this->a = a;
    }
    
    // function that does stuff with both A and B nums
    int add() {
        return num + a->num;
    }
};

inline A::A() {
    b = new B(this);
}

int main()
{
    A thing;
    printf("%d",thing.b->add());
    return 0;
}

推荐阅读