基本上我在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)。
答案 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;
}
}