2

c++ header file "a.h" :

#pragma once
#include "b.h"

struct A {
    void f() {
        b.f();
    }
    B b;
    int i;
};

c++ header file "b.h" :

#pragma once
#include"a.h"

struct B {
    void f() {
        int x = a->i; //error occur
    }
    A* a;
};

"test.cpp":

#include "a.h"

int main(){
    A a;
    a.f();
}

Call 'a->i' in B will trigger error.Why?How to solve it.

bruno
  • 32,421
  • 7
  • 25
  • 37
haskeller
  • 141
  • 4

1 Answers1

2

This is a known issue with the include paradigm that C++ inherited from C. You cannot solve this.

What you have to do is remove the line #include "a.h" in file b.h and forward declare struct A; before using it in B.

b.h

#pragma once

struct A;
struct B {
    void f();
    A* a;
};

b.cpp

#include "b.h"
#include "a.h"

void B::f() {
    int x = a->i;
}

Otherwise you have circular inclusion.

bitmask
  • 32,434
  • 14
  • 99
  • 159