tags:

views:

59

answers:

2

Hello i have structures declared in the same Header file that need eachother.

struct A; // ignored by the compiler
struct B{
  A _iNeedA; //Compiler error Here
};

struct A { 
  B _iNeedB;
};

this work normally

class A;
class B{
  A _iNeedA;
};

class A { 
  B _iNeedB;
    };

// everything is good

Thank you very much!

+7  A: 

This can’t work: A contains B contains A contains B contains …. Where to stop?

All you can do to model cyclic dependencies is use pointers:

class A;

class B {
    A* _iNeedA;
};

class A {
    B* _iNeedB;
};

Now the classes don’t contain each other, merely references to each other.

Furthermore, you need to pay attention that you can’t use things you haven’t defined yet: in the above code, you have declared A before defining B. So it’s fine to declare pointers to A in B. But you cannot yet use A before defining it.

Konrad Rudolph
A: 

I answer my own question.

the fact is what im doing is not exactly what i posted but i thougt it was the same thing, actually i'm using operators that take arguments. Thoses operators body must be defined after my structs declarations (outside the struct), because struct B don't know yet struct A members...

I said it was working with classes because with classes we usualy use CPP file for methods definition, here i am not using any cpp file for methods i use in my structs

I was about to delete this post but you guys are too fast ;),

Here an example

struct A; 

struct B { 
int member;
bool operator<(const A& right); //body not defined

}; 

struct A { 

int member;
   bool operator<(const B& right)
   {
      return  this->member < B.member;
   }
}; 

 bool B::operator<(const A& right) //define the body here after struct A definition
{
    return  this->member < A.member;
}
MiniScalope