NonTemplate Function Friend of Class Template
On Lippman p656 I read:
A nontemplate function or class can be a friend to a class template:
template<class Type> class Bar {
friend class Foobar;
friend void fcn();
};
开发者_StackOverflow社区I wonder what all this means. If fcn
is made a friend it is becuase you want it to access the private members of Bar
, but how can it access them it if has not got any Bar
object passed into as a parameter?
Can somebody please enlighten me on this?
Being afriend
of a class X
means the friend (whether it's function, or class) has access to all private and protected members of the class X
.
In your example, the class Foobar
and the function fcn
has access to private and protected members of the class Bar
.
Now the question is:
how can it access them it if has not got any Bar object passed into as a parameter?
Well, it can access if it has instance of Bar
. For example.
void fcn()
{
Bar<int> bar;
bar.PrivateFun(); //okay even if PrivateFun is a private function of Bar
bar.PrivateData = 10; //okay even if PrivateData is a private data of Bar
}
Just to emphasize the difference, consider this another function:
void g()
{
Bar<int> bar;
bar.PrivateFun(); //compilation error - g() is not a friend of Bar!
bar.PrivateData = 10; //compilation error - g() is not a friend of Bar!
}
Hope it helps you understanding what it means to have access to private members of a class, and what it means to be a friend
of a class!
Perhaps there is a global Bar<T>
which it can access- just because there is no obvious parameter doesn't mean that it can't access a Bar<T>
. Also, that's ill-formed syntax.
精彩评论