从另一个类 C++ 访问命名空间中的私有静态成员变量

发布于 2025-01-11 22:25:49 字数 665 浏览 3 评论 0 原文

我有一个问题。在下面的示例中,命名空间 a 内有一个类 A 的名为 private_b 的静态私有成员变量。然后我尝试从类 B 访问该变量,我已将其声明为类 Afriend,但它并没有不起作用,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 位于该命名空间内没有意义。我在互联网上搜索过这个问题,但找不到这个确切的案例,或者找不到这个案例的解决方案。

I have a problem. In the following example, there is a static private member variable called private_b of class A inside namespace a. And then I'm trying to access that variable from class B, which I have declared to be a friend of class A, but it doesn't work, with a compile error from GCC:

error: ‘B* a::A::private_b’ is private within this context

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
    }
};

I don't understand why I can't access it, and how to get around this problem. I really want class A to be inside that namespace, and class B doesn't make sense to be inside that namespace. I searched for this on the internet, but couldn't find this exact case, or couldn't find a solution for this case.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

恏ㄋ傷疤忘ㄋ疼 2025-01-18 22:25:50

friend 类 B; 在同一命名空间 a 中声明与 B 的友谊。您可能需要friend class ::B;

注意,friend class B;并不引用全局前向声明class B,它在关键字class B >朋友。

friend class B; declared friendship with B in the same namespace a. You may want friend class ::B;.

Note, friend class B; does not refer to the global forward declaration class B, it has own forward declaration class B after the keyword friend.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文