我不明白这一行 - 解除引用一个私有成员变量的地址或什么? [英] I can't understand this line - dereferencing an address of private member variable or what?

查看:140
本文介绍了我不明白这一行 - 解除引用一个私有成员变量的地址或什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前问过一个问题关于访问STL适配器的底层容器。我得到了非常有帮助的答案:

 模板< class T,S类,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;不幸的是,我不明白这一行:







$ b

  return q。*& HackedQueue :: c; 

这行代码是什么?此外,该行如何访问传递给函数 Container

priority_queue

解决方案

想像这样:

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

首先,你有HackedQueue :: c,它只是一个成员变量的名字。然后你取& HackedQueue :: c,它是一个指向那个成员变量的指针。接下来你取 q ,这只是一个对象引用。然后你使用绑定指针到成员引用操作符。* 使用 q 作为



至于私人成员问题, priority_queue :: c 只受保护,不是私人的,所以当你从 priority_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?

解决方案

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.

这篇关于我不明白这一行 - 解除引用一个私有成员变量的地址或什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆