简体   繁体   English

类模板的NonTemplate函数之友

[英]NonTemplate Function Friend of Class Template

On Lippman p656 I read: 在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();
}; 

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? 如果fcn成为朋友,是因为您希望它访问Bar的私有成员,但是如果没有将任何Bar对象作为参数传递,它将如何访问它们呢?

Can somebody please enlighten me on this? 有人可以启发我吗?

Being a friend 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 . 作为一个friend一类的X指的朋友(无论是功能,或类)可以访问类的所有private和protected成员X

In your example, the class Foobar and the function fcn has access to private and protected members of the class Bar . 在您的示例中,类Foobar和函数fcn可以访问Bar类的私有成员和受保护成员。

Now the question is: 现在的问题是:

how can it access them it if has not got any Bar object passed into as a parameter? 如果没有将任何Bar对象作为参数传递,它将如何访问它们?

Well, it can access if it has instance of Bar . 好吧,如果它具有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! 希望它可以帮助您了解访问班级私人成员的含义以及成为班级friend的含义!

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> . 也许存在一个可以访问的全局Bar<T>仅仅因为没有明显的参数并不意味着它不能访问Bar<T> Also, that's ill-formed syntax. 而且,这是格式错误的语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM