Cross-reference classes cause an "incomplete type" error

I have a situation where A has a reference to the class C defined inside B, and C has an instance of class B.

When I try to compile the code below, I get a " field a has incomplete type". I assume this is because the compiler does not know how much memory it should allocate for instance A.

class A;

class B {
public:
  class C {
    A a;
  };
};

class A {
  A(const B::C& _c) 
    : c(_c)
  {}
  const B::C& c;
};

But when I try to compile this, I get " C in class B does not name a type":

class B;
class B::C;

class A {
  A(const B::C& _c) 
    : c(_c)
  {}
  const B::C& c;
};


class B {      
public:
  class C {
    A a;
  };
};

How can I convince the compiler that B::Cis a real type?

+3
source share
2 answers

, , :

class B {
public:
  class C; // Forward declaration
};

class A {
  A(const B::C& _c) 
    : c(_c)
  {}
  const B::C& c;
};

class B::C {
  A a;
  C() : a(*this) {}    // Thanks Nim for pointing this out!
};

, , , . , .

+5

A : .

B::C, , . C B: , - * .

* , , , , A .

+2

Source: https://habr.com/ru/post/1770547/


All Articles