从另一个类 C++ 访问命名空间中的私有静态成员变量
我有一个问题。在下面的示例中,命名空间 a
内有一个类 A
的名为 private_b
的静态私有成员变量。然后我尝试从类 B
访问该变量,我已将其声明为类 A
的 friend
,但它并没有不起作用,GCC 出现编译错误:
错误:“B* a::A::private_b”在此上下文中是私有的
class B;
namespace a {
class A {
private:
static B* private_b;
friend class B;
};
B* A::private_b = nullptr;
}
class B {
public:
void foo() {
B* foo = a::A::private_b; // Error here
}
};
我不明白为什么我无法访问它,以及如何解决这个问题。我真的希望类 A
位于该命名空间内,而类 B
位于该命名空间内没有意义。我在互联网上搜索过这个问题,但找不到这个确切的案例,或者找不到这个案例的解决方案。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
friend 类 B;
在同一命名空间a
中声明与B
的友谊。您可能需要friend class ::B;
。注意,
friend class B;
并不引用全局前向声明class B
,它在关键字class B >朋友。
friend class B;
declared friendship withB
in the same namespacea
. You may wantfriend class ::B;
.Note,
friend class B;
does not refer to the global forward declarationclass B
, it has own forward declarationclass B
after the keywordfriend
.