How to include the same class in multiple files?

Asked

Viewed 294 times

3

Because I can’t include the same class in multiple type files like this:

#include "familia.h"
class pessoa{

private:
familia *f;
};

-----
#include "pessoa."

class familia{
private:
pessoa *p;
};
  • Take a look: https://www.vivaolinux.com.br/topico/C-C++/Referencia-crossed++

  • Did the answer solve your problem? Do you think you can accept it? If you don’t know how you do it, check out [tour]. This would help a lot to indicate that the solution was useful to you and to give an indication that there was a satisfactory solution. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

3

You are having problems because they are interdependent. You must ensure that one does not call the other indefinitely. You need to ensure that there is a class statement (you don’t need to declare it all, but that it is made explicit):

#ifndef PESSOA_H
#define PESSOA_H
class Familia;
class Pessoa {
    Familia *f;
};
#endif

And then

#ifndef FAMILIA_H
#define FAMILIA_H
class Pessoa;
class Familia {
    Pessoa *p;
};
#endif

I put in the Github for future reference.

This is called forward declaration.

Don’t forget to put guards on .cpp not to load duplicity headers.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.