我应该如何在嵌套 class 中正确使用友元声明?
How should I properly use a friend declaration in a nested class?
例如,假设我编写了如下代码:
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
class 的 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
}
关于您的代码问题;在 B
class 中的 friend int A::foo(B &b);
行,它不知道函数 A::foo
。因此我们需要在class B
之前转发声明int foo(B &);
。然后是问题; A::foo(B &)
是否知道 B
。也没有。但幸运的是,C++ 也允许通过向前声明 classes 来拥有不完整的类型。也就是说,循序渐进,你可以达到你想要的目标。
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;
}
例如,假设我编写了如下代码:
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
class 的 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
}
关于您的代码问题;在 B
class 中的 friend int A::foo(B &b);
行,它不知道函数 A::foo
。因此我们需要在class B
之前转发声明int foo(B &);
。然后是问题; A::foo(B &)
是否知道 B
。也没有。但幸运的是,C++ 也允许通过向前声明 classes 来拥有不完整的类型。也就是说,循序渐进,你可以达到你想要的目标。
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;
}