例如,假设我编写了如下代码:
class A
{
private:
class B
{
private:
int a;
friend int A::foo(B &b);
};
int foo(B &b)
{
return b.a;
}
};
自 a
在B
是私有(private)的,使用 a
在函数中 foo
的 A
, 我会用 friend
这样foo
实际可以访问a
.
但是这段代码给出了无法访问 a
的错误.代码有什么问题,我应该如何在保留a
的情况下更改代码私有(private)和A
不是 B
的 friend ?或者有更好的方法吗?
最佳答案
如果您只想获取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
}
关于你的代码问题;在 B
类的 friend 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;
}
关于c++ - 我应该如何在嵌套类中正确使用友元声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53019191/