Friend function in separate files

Hello,

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?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * Path: ./one.hpp 
 */
#ifndef _ONE_HPP
#define _ONE_HPP 1

#include "two.hpp"

class One {
private:
    int a, b;    
    friend void Two::print(One&);
public:
    One() : a(1), b(2) {}
};

#endif


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
 * Path: ./two.hpp
 */

#ifndef _TWO_HPP
#define _TWO_HPP 1

class One;
class Two {
public:
    void print(One&);
};

#endif


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
 * Path: ./two.cpp
 */
#include "one.hpp"
#include "two.hpp"
#include <iostream>
using std::cout;
using std::endl;

void Two::print(One& x)
{
    cout << "a is " << x.a << endl;
    cout << "b is " << x.b << endl;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * Path: ./friend.cpp
 */
#include "one.hpp"
#include "two.hpp"

int main()
{
    One obj1;
    Two obj2;
    obj2.print(obj1);
}
Last edited on
Just out of curiosity... why does class Two know how to print class One, but class One doesn't know how
to print itself?
Topic archived. No new replies allowed.