我在 Lippman p656 上读到:
A nontemplate function or class can be a friend to a class template:
template<class Type> class Bar {
friend class Foobar;
friend void fcn();
};
我想知道这一切意味着什么。如果将 fcn
设为好友,那是因为您希望它访问 Bar
的私有(private)成员,但如果没有任何 Bar,它如何访问它们
作为参数传入的对象?
有人可以请教我这个吗?
最佳答案
成为类 X
的 friend
意味着 friend (无论是函数还是类)可以访问类 X 的所有私有(private)和 protected 成员
。
在您的示例中,类 Foobar
和函数 fcn
可以访问类 Bar
的私有(private)和 protected 成员。
现在的问题是:
how can it access them it if has not got any Bar object passed into as a parameter?
嗯,如果它有 Bar
的实例,它就可以访问。例如。
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
}
为了强调区别,请考虑另一个函数:
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!
}
希望它能帮助您理解访问一个类的私有(private)成员意味着什么,以及成为一个类的 friend
意味着什么!
关于c++ - 类模板的非模板函数友元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5555696/