Hi, I have two simple class that I made just to understand how friend class works. I am confused as to why this doesn't compile and also would the Linear class have access to the struct inside Queues class?
Linear.h
1 2 3 4 5 6 7 8
template<typename k, typename v >
class Linear
{
public:
//Can I create a instance of Queues here if the code did compile?
private:
};
Linear.cpp
#include "Linear.h"
Queues.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include "Linear.h"
template<typename k, typename v >
class Linear;
template<typename x>
class Queues
{
public:
private:
struct Nodes{
int x;
};
//Does this mean I am giving Linear class access to all of my Queues class variable or is it the opposite ?
friendclass Linear<k,v>;
};
#include"Queues.h"
My errors are
Queues.h:15: error: `k' was not declared in this scope
Queues.h:15: error: `v' was not declared in this scope
Queues.h:15: error: template argument 1 is invalid
Queues.h:15: error: template argument 2 is invalid
Queues.h:15: error: friend declaration does not name a class or function
I'm not an expert on templates but here's what I've got
The error comes from the fact that class Queues doesn't know what k and v are. Linear does, but you have to tell that to Queues. You can do
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
template<typename k, typename v >
class Linear;
template<typename x, typename k, typename v>
class Queues
{
public:
private:
struct Nodes{
int n; // You declared a variable that had the same name as the template type. That's a no-no
} list; // You must create an instance of Nodes or Linear will have access to an empty class
// Linear will have access to protected/private members of Queues, so it will be able to access list
friendclass Linear<k, v>;
};
To create data of type Queues inside Linear you need to put the declaration of Queues before the declaration of Linear, or it will not know that it is a type. So it's not Queues.h that needs to include Linear.h, it's the opposite (by the way, you still need to forward declare Linear to be able to make it a friend class).