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

时间:2013-08-07 11:42:58

标签: 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;
}

在A类的void f()之前加上“public:”进行编译。那么李普曼错了吗?

P.S。 Lippman的代码是这样的:

//...
class Triangular_iterator
{
//...
private:
void check_integrity() const;
//...
};

//...

class Triangular
{
//...
friend void Triangular_iterator::check_integrity();
//...
};

//...

2 个答案:

答案 0 :(得分: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();
};

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

有关示例,请参阅here

答案 1 :(得分:4)

可以将类A的私有成员函数声明为类B的朋友。为此,必须将类B声明为类A的朋友(否则,类B不能看到类A的私有成员函数) :

class A
{
    friend class B;
    void f();
};

class B
{
    friend void A::f();
};

在C ++中,朋友的概念来自于我允许我宣称为朋友的人比非朋友对待我的事实。它不涉及以非朋友的方式对待我宣称为朋友的人。