我无法理解这一行 - 取消引用私有成员变量的地址还是什么?

发布于 2024-08-04 11:22:09 字数 868 浏览 0 评论 0原文

我不久前问了一个问题 关于访问STL适配器的底层容器。我得到了一个非常有用的答案:

template <class T, class S, class C>
    S& Container(priority_queue<T, S, C>& q) {
        struct HackedQueue : private priority_queue<T, S, C> {
            static S& Container(priority_queue<T, S, C>& q) {
                return q.*&HackedQueue::c;
            }
        };
    return HackedQueue::Container(q);
}

int main()
{
    priority_queue<SomeClass> pq;
    vector<SomeClass> &tasks = Container(pq);
    return 0;
}

不幸的是,我无法理解这一行:

return q.*&HackedQueue::c;

这条线有什么作用?另外,该行如何访问传递给函数 Containerpriority_queue 中的私有容器?

I asked a question while ago about accessing the underlying container of STL adapters. I got a very helpful answer:

template <class T, class S, class C>
    S& Container(priority_queue<T, S, C>& q) {
        struct HackedQueue : private priority_queue<T, S, C> {
            static S& Container(priority_queue<T, S, C>& q) {
                return q.*&HackedQueue::c;
            }
        };
    return HackedQueue::Container(q);
}

int main()
{
    priority_queue<SomeClass> pq;
    vector<SomeClass> &tasks = Container(pq);
    return 0;
}

Unfortunately, I couldn't understand this line:

return q.*&HackedQueue::c;

What does this line do? Also, how could that line access the private container in priority_queue that is passed to the function Container?

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

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

发布评论

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

评论(1

风月客 2024-08-11 11:22:09

可以这样想:

(q).*(&HackedQueue::c);

首先,您有 HackedQueue::c,它只是一个成员变量的名称。然后,您获取 &HackedQueue::c,它是指向该成员变量的指针。接下来,您采用q,它只是一个对象引用。然后,使用“通过引用将指针绑定到成员”运算符 .* 来绑定成员变量指针引用的成员变量,使用 q 作为 this

至于私有成员问题, priority_queue::c 仅受保护,而不是私有,因此当您从 priority_queue 派生时,您可以访问它,这应该不足为奇其受保护的成员。

Think of it like this:

(q).*(&HackedQueue::c);

First, you have HackedQueue::c, which is just the name of a member variable. Then you take &HackedQueue::c, which is a pointer to that member variable. Next you take q, which is just an object reference. Then you use the "bind pointer to member by reference" operator .* to bind the member variable referred to by the member-variable pointer using q as the this.

As to the private member issue, priority_queue::c is only protected, not private, so it should come as no surprise that when you derive from priority_queue, that you can access its protected members.

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