【问题标题】:structure circuliar depenency结构循环依赖
【发布时间】:2020-04-19 10:58:36
【问题描述】:

我有两个结构:

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

我该如何解决?

【问题讨论】:

    标签: c++ struct circular-dependency


    【解决方案1】:

    您可以通过将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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-13
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-12
      相关资源
      最近更新 更多