Inside FileTwo.h
#ifndef FILETWO
#define FILETWO
#include"FileOne.h"
class FileOne ;
class FileTwo
{
public:
int Test(FileOne One){
return (One.var1+One.var2);}
FileTwo(void);
~FileTwo(void);
};
#endif
Inside FileOne.h
#ifndef FILEONE
#define FILEONE
#include"FileTwo.h"
class FileTwo ;
class FileOne
{
private:
int var1 , var2 , var3 ;
public :
friend int FileTwo::Test(FileOne One);
FileOne(){
var1= 12;var2 = 24;
}
};
#endif
Inside main.cpp
#include<iostream>
using namespace std ;
#include"FileOne.h"
#include"FileTwo.h"
int main(){
FileOne one ;
FileTo two ;
cout<<two.Test(one);
}
During compilation i got the following error
1-- error C2027: use of undefined type 'FileOne' c:\users\e543925\documents\visual studio 2005\projects\myproject\filetwo.h
2--error C2027: use of undefined type 'FileOne' c:\users\e543925\documents\visual studio 2005\projects\myproject\filetwo.h
3--error C2228: left of '.var1' must have class/struct/union c:\users\e543925\documents\visual studio 2005\projects\myproject\filetwo.h
4--error C2228: left of '.var2' must have class/struct/union c:\users\e543925\documents\visual studio 2005\projects\myproject\filetwo.h
I have found one workaround like definning the Test function inside FileTwo.cpp . But i want to know how the above issue can be resolved inside header file .
Your problem here is that you are including both files in each other. When your compiler goes to parse
FileOne.h, it includesFileTwo.h, so it reads that, skipsFileOne.h(thanks to the include guards; otherwise, you would go into an infinite loop) and tries to use classFileOne, which is not yet defined.In practice, this is just as if you had not included
FileOne.hinFileTwo.h; you cannot call methods onOnebecause its type (FileOne) is not yet defined. Nothing to do with friend classes. Or not yet (you will get into this problem later).From your code, it looks like you want to use class
FileTwoto testFileOne. In this case,FileOnedoes not really need to know much aboutFileTwo, just allow it to look at its innards (aka make it a friend). So your code can boil down to:FileOne.h:
FileTwo.h: