-
friend question
i want to make class A friend of class B, so when i declare an instance of A within B its private members will also in handy. but things go wrongly when i compile it, my code is right below:
Code:
template <class T>
class A
{
friend B<T>;
public:
//
private:
T data;
};
template <class T>
class B
{
public :
//
private:
A<T>* a;
}
i just can not figure out the problem, any ideas ?
btw, i am with Dev-C++ 5, thanx.
-
Code:
friend B<T>;
T data;
A doesn't know what a T is.
A isn't templated
You need to either tell what kind of template B needs to be by giving it a known type and create that member data so that it is of that chosen type, or template A itself. Also, by the looks of what you're trying to do, you might want to try out private inheritance, although it may not be necessary.
-
sorry i forgot to add template line above class A, even i add that line my compiler will still report an error, any suggestions ?
-
well, A need's to know what class B looks like since it has the friend declaration, so B needs to be declared before A....but...B needs to know what A looks like since it has A as a private member, so A needs to go first. Curse you circular dependance!
if you put a forward declarations of B infront of A, all should be fine. It just tells the compiler that B is indeed a class, but it's defined somewhere else.
Code:
template <class T> class B;
By the way, it's become standard practice to use template <typename> instead of <class>, but to my knowledge there is no difference.
-
oh thanx let me try it. but it is strange that my book didnt mention anything about this, mmm...
-
my god i tried that but failed either. these are what my code looks like:
Code:
template <class T>
class Stack;
template <class T>
class StackNode
{
friend Stack<T>;
public :
//
private :
T __data;
StackNode* __next;
};
template <class T>
class Stack
{
//
};
what's wrong again ???
-
Nothing seems to be wrong, and that snippet compiled fine on my machine. If it's not the same error, I ask that you post what the error messages are. Other than that, I can only suggest that you make StackNode a struct instead of a class with private fields, making the friend declaration unecessary. It wouldn't solve the problem, merely get around it.