如何将方法声明为“朋友”?

时间:2013-09-12 00:11:46

标签: c++

基本上我在namspace下有两个类,我想给一个类的一个方法(称之为B::fun)访问另一个类的私有成员(称之为class A )。但是,我似乎无法让它发挥作用。这是一个说明问题的简单示例:

namespace ABC // this could be global too
{
    class A;

    class B
    {
    public:
        int fun(A member);
    };

    class A
    {
    public:
        friend int B::fun(A member);

    private:
        int aint;
    };

    int B::fun(A member)
    {
        return member.aint; // error: member ABC::A::aint is inaccessible
    }
}

为什么我会收到此错误?

注意:似乎是编译器问题(使用VC ++ 11)。

2 个答案:

答案 0 :(得分:3)

实际上,使用G ++ 4.8.1和CLang ++ 3.3我在friend行中收到错误:

g ++ error: 'int ABC::B::fun(ABC::A)' is private

clang ++ error: friend function 'fun' is a private member of 'ABC::B'

也就是说,错误是ABC::B::fun()是私有的,因此朋友声明失败,然后您发出信号的行因此而失败。

这种情况发生的原因只是因为你无法让一个你无法访问的朋友。

解决方案是让ABC::B::fun()公开,或将整个B或类似的东西交给朋友。

顺便说一下,命名空间与你的错误没有任何关系,但IMO如果你的朋友声明只是简单的话会更清楚:

friend int B::fun(A member);

因为您已经在名称空间ABC内。

答案 1 :(得分:2)

A

中更改好友声明
class A {
    friend class B;
    int aint;
};

或者,要仅与单一方法相关,您需要将A设为B的朋友,因为您friend的方法是私有的。或者你可以公开fun(A)

namespace ABC
{
    class A;

    class B
    {
        friend class A;
        int fun(A member);
    };

    class A
    {
        friend int B::fun(A);
        int aint;
    };

    int B::fun(A member)
    {
        return member.aint;
    }
}