如何在嵌套类中正确使用友元声明?
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
类的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;
}
相关文章:
- 如何在嵌套类中正确使用友元声明?
- 类模板中文本运算符的友元声明
- 模板和隐式构造函数的类定义之外的友元声明
- 如何将友元声明用于具有约束的模板类
- 模板化友元声明在 G++ 5.4.0 下不起作用 - 编译器错误或错误代码
- 友元声明阻止外部函数访问类的私有部分
- C++:友元声明'声明一个非模板函数
- 友元声明及其表示的实体
- 嵌套类中需要前向声明的友元声明
- 多参数模板不能很好地处理友元声明
- 友元声明和显式模板实例化声明
- 为什么标准禁止部分专门化的友元声明
- is_constructible和is_destructibble不受友元声明的影响
- Pimpl习语和内部对象协作,无需友元声明
- C++中的友元声明-公共和私有之间的区别
- 单个成员而不是整个类的友元声明
- 关于 C++ 中友元声明的基本内容错误
- 有没有办法避免模板友元声明的外部可见性
- 如何解决c++中友元声明的循环依赖
- 指定默认实参的友元声明必须是定义