I am trying out friend functions in different files to see how it work. However, I am having problems compiling it with error after error. Well now I'm done to one error again, please have a look at my code:
/* ---------- classOne.h ---------- */
#ifndef CLASSONE_H_
#define CLASSONE_H_
#include "ClassTwo.h" // ClassOne has to know about ClassTwo before it can be friends with it
using namespace std;
class ClassOne {
private:
int m_a;
int m_b;
public:
ClassOne(int a, int b);
void printValuesOne();
//friend class ClassTwo;
friend void ClassTwo::twoPrintsOne(const ClassOne& c);
};
-
/* ---------- classTwo.h ---------- */
#ifndef CLASSTWO_H_
#define CLASSTWO_H_
using namespace std;
class ClassOne;
class ClassTwo {
private:
int m_c;
int m_d;
public:
ClassTwo(int c, int d);
void printValuesTwo();
void twoPrintsOne(const ClassOne& c);
};
#endif
-
/* ---------- classOne.cpp ---------- */
#include <iostream>
#include "classOne.h"
using namespace std;
ClassOne::ClassOne(int a, int b) {
m_a = a;
m_b = b;
}
/*
* The method takes a ClassOne object and prints the value of it's members m_a and m_b.
*/
void ClassOne::printValuesOne() {
cout << "m_a: " << m_a << " " << "m_b: " << m_b << endl;
}
-
/* ---------- classTwo.cpp ---------- */
#include <iostream>
#include "classTwo.h"
using namespace std;
ClassTwo::ClassTwo(int c, int d) {
m_c = c;
m_d = d;
}
void ClassTwo::printValuesTwo() {
cout << "m_c: " << m_c << " " << "m_d: " << m_d << endl;
}
void ClassTwo::twoPrintsOne(const ClassOne& c) {
cout << "ClassTwo: " << "m_a:" << c.m_a << " " << "m_b: " << c.m_b << endl;
}
I want ClassTwo's function twoPrintsOne to print out the private member variables of ClassOne.
I don't understand why I get this error:
In member function ‘void ClassTwo::twoPrintsOne(const ClassOne&)’:
classTwo.cpp:22:37: error: invalid use of incomplete type ‘const class ClassOne’
cout << "ClassTwo: " << "m_a:" << c.m_a << " " << "m_b: " << c.m_b << endl;
Well I guess the forward declaration of class ClassOne
in classTwo.h means that classTwo.cpp including means that it can make any assumptions about ClassOne, such as what functions are in that class right? If so, then I don't see any other way to do this. Except including the file and have this circular dependency problem.