I have two classes like this:

class B;

class A {
public:
  int a, b;
  B *b;
public:
  int getctxt()
  {
     b->getctxt1();
  }
}

Class B {
public:  
  int c,d;
  A *a; 
  getctxt1()
  {
      /* something */
  }   
}

main()
{
  B *b = new B();
  A *a = new A();
  b->a = a;
  a->b = b;
}

But when I try to compile, it says

invalid use of incomplete type ‘struct A’.

Can anyone tell me how to solve this?

有帮助吗?

解决方案

Inline class member function definitions are parsed as if they appeared right after the class definition. Of course B isn't defined at that point. So move the member function definition for A::getctxt out of the definition of class A:

class B;

class A { int getctxt(); /* ... */ };

class B { /* ... */ };

int A::getctxt()
{
    b->getctxt1();   // at this point, *b has complete type!
    return -35;
}

其他提示

This is the reason why it is recommended to separate your classes in a .h file and a .cpp file. When you write class B;, you are telling the compiler that there is a class called B, but that's it, the compiler does not know what is inside this class. When the compiler reaches the line b->getctxt1();, it knows that b is an instance of B, but it does not know if getctxt1() is a method of B, because that is below. If you are writing all in a single file, you should first write all the declarations, and then all the implementations.

didn't anyone notice Class B syntax error? lowercase class is correct. and those two public members in A with the same name int b and B *b.

once you remove those and finish class definitions with semicolons, add a void type to the void getctxt1() that is missing it in B.

just define functions as they should be defined. not inline without a reason that you know which is!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top