Pergunta

If the class G is in the namespace GSpace and it needs to be friends with the class M in the global namespace what do you have to do? I thought this would work:

/////////////////////M.h//////////////////////
#include "GFile.h"

class M
{
   public:
      friend class GSpace::G; // doesn't work, throws error
}

After researching on StackOverflow a bit, I found this answer https://stackoverflow.com/a/3843743/1797424

/////////////////////M.h//////////////////////

namespace GSpace 
{
   class G;
}

class M
{
   public:
      friend class GSpace::G; // works, no error
   private:
      GSpace::G gClassMember; // errors: "M uses undefined class GSpace::G"
};
// Note that G.h includes M.h so I do not include it here, 
// instead I have it included in M.cpp

That does work for getting the class friended. However, it creates an issue when I actually declare a class member using that type, because the class is not defined. GFile.h

Am I misunderstanding how #include and forward declaration behaves, or is it some kind of implementation issue on the side of the compiler (not likely, I'm assuming)?

Foi útil?

Solução

  • Because your member is not a pointer or reference, the compiler needs to know the size of G. You can't use a forward declaration.
  • As noted in the comment, you need to qualify G with the namespace.

Here is code which compiles for me:

namespace GSpace
{
   class G
   {
   };
}

class M
{
   public:
      friend class GSpace::G;
   private:
      GSpace::G gClassMember;
};

int main() {return 0;}

Outras dicas

Try the following

namespace GSpace
{
   class G;
}

class M
{
   public:
      friend class GSpace::G; 
}

namespace GSpace
{
   class G { /* definition of the class */ };
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top