c++ - 类模板的非模板函数友元

标签 c++ class templates function

我在 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/

相关文章:

C++ std::set 自定义比较器

android - 如何将 C++ 源代码解析为 obj?

templates - 获取当前模板名称?

c++ - 介子项目 : can I have part of the source located elsewhere?

c++ - GCC - 'sizeof' 之前的预期不合格 ID - Android NDK 中的 IT++ 4.2

c++ - "inlined"类的惩罚

使用模板链表和指针传递的 C++ 未解析外部符号

templates - 用数据库的设计替换 Lotus Notes 模板的设计(或使数据库成为模板)

javascript - 如何按类和该 div 中的类来定位/选择 div

Python 类构造函数返回空值