可以将A类的私有成员函数声明为B类的朋友吗?

Fel*_*lix 2 c++

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)

bas*_*h.d 5

您不能在"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)

在现实生活中,你也无法决定是否违背自己的意愿成为某人的朋友!

请看这里的例子.

  • @juanchopanza这不是错误的方向,因为需要两个方向:`A`需要让'B`成为朋友,这样'B`就可以让'A :: f`成为朋友. (3认同)