0

我有两个结构:

struct B;
struct A {
    B *b;
    void Func() {
        std::cout << b->x << std::endl;
    }
};
struct B {
    A a;
    float x;
    void Func() {
        a.Func();
    }
};

当我尝试编译它时,我收到以下错误:

Error C2027 use of undefined type 'B'
Error C2227 left of '->x' must point to class/struct/union/generic type

我该如何解决?

4

1 回答 1

3

您可以通过将Func类声明外部的定义移动到B完全定义的位置来解决此问题,例如:

struct B;
struct A {
    B *b;
    // Only declare Func, do not provide definition
    void Func();
};
struct B {
    A a;
    float x;
    void Func() {
        a.Func();
    }
};

// Define Func where the full definition of B is available
void A::Func() {
    std::cout << b->x << std::endl;
}
于 2020-04-19T11:05:15.093 回答