Lippman的Essential C++第4.7节就是这样做的.但我不知道为什么这段代码不能编译:
#include <iostream>
using namespace std;
class A
{
void f();
//other members...
};
class B
{
//other members...
friend void A::f();
};
int main()
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在A类中的void f()之前放置"public:"进行编译.那么李普曼错了吗?
ps Lippman的代码是这样的:
//...
class Triangular_iterator
{
//...
private:
void check_integrity() const;
//...
};
//...
class Triangular
{
//...
friend void Triangular_iterator::check_integrity();
//...
};
//...
Run Code Online (Sandbox Code Playgroud)
您不能在"B级"中将"A级"的功能或成员声明为"B级"的朋友.
你必须允许"B级"成为"A级" A::f()的朋友,然后成为"B级"的朋友:
class A
{
void f();
friend class B; //allow B access to private (protected) members and functions
};
class B
{
friend void A::f();
};
Run Code Online (Sandbox Code Playgroud)
在现实生活中,你也无法决定是否违背自己的意愿成为某人的朋友!
请看这里的例子.