如何在嵌套类中正确使用友元声明?

How should I properly use a friend declaration in a nested class?

本文关键字:友元 声明 嵌套      更新时间:2023-10-16

例如,假设我做了一个这样的代码:

class A
{
private:
class B
{
private:
int a;
friend int A::foo(B &b);
};
int foo(B &b)
{
return b.a;
}
};

由于B中的a是私有的,因此要在A的功能foo中使用a,我将使用friend,以便foo可以实际访问a

但是,此代码给出的错误是它无法访问a。代码有什么问题,我应该如何在保持a私密性和A不是B的朋友的同时更改代码?还是有更好的方法?

如果你只想获取B类的a,你需要一个getter函数。这应该是最简单的方法。

class B
{
private:
int a;
public:
// provide getter function
const int& getMember_a()const { return a; }
};

并在foo函数中

const int& foo(const B &b)const 
{
return b.getMember_a(); // call the getter to get the a
}

关于你的代码问题;在类Bfriend int A::foo(B &b);行,它不知道函数A::foo。因此我们需要在类B之前转发声明int foo(B &);。然后是问题;A::foo(B &)是否知道B.也没有。但幸运的是,C++也允许通过前向声明类来拥有不完整的类型。这意味着,按照方式,你可以实现你想要的目标。

class A
{
private:
class B;      // forward declare class B for A::foo(B &)
int foo(B &); // forward declare the member function of A
class B
{
private:
int a;
public:
friend int A::foo(B &b);
};
};
// define, as a non-member friend function
int A::foo(B &b)
{
return b.a;
}