I need to use friend functions into two classes in separate files. I compiled and run the following sample program without problems but when I try to separate it into different files I get several compile errors related to the classes declaration.
------- friend1.cc -----------
class ONE;
class TWO
{
public:
void print(ONE& x);
};
class ONE
{
private:
int a, b;
friend void TWO::print(ONE& x);
public:
ONE() : a(1), b(2) { }
};
void TWO::print(ONE& x)
{
cout << "a is " << x.a << endl;
cout << "b is " << x.b << endl;
}
int main()
{
ONE xobj;
TWO yobj;
yobj.print(xobj);
}
In separated files:
------- one.h ---------
//class TWO;
//#include "two.h"
class ONE
{
private:
int a, b;
friend void TWO::print(ONE& x);
public:
ONE() : a(1), b(2) { }
};
------- one.cc --------
#include "one.h"
void TWO::print(ONE& x)
{}
------- two.h ---------
class ONE;
class TWO
{
public:
void print(ONE& x);
};
------- two.cc --------
#include "two.h"
void TWO::print(ONE& x)
{
cout << "a is " << x.a << endl;
cout << "b is " << x.b << endl;
}
------- friend2.cc ----
#include "one.h"
#include "two.h"
int main()
{
ONE xobj;
TWO yobj;
yobj.print(xobj);
}
These are the compilation errors:
$ g++ one.cc two.cc friend2.cc -o friend
In file included from one.cc:1:
one.h:10: error: âTWOâ has not been declared
one.cc:3: error: âTWOâ has not been declared
two.cc: In member function âvoid TWO::print(ONE&)â:
two.cc:4: error: invalid use of incomplete type âstruct ONEâ
two.h:4: error: forward declaration of âstruct ONEâ
two.cc:5: error: invalid use of incomplete type âstruct ONEâ
two.h:4: error: forward declaration of âstruct ONEâ
In file included from friend2.cc:2:
one.h:10: error: âTWOâ has not been declared
Could you get me ideas in order to get the best solution?