代码之家  ›  专栏  ›  技术社区  ›  Jason R. Mick

在c中使用“This”指针++

  •  1
  • Jason R. Mick  · 技术社区  · 14 年前

    但我发现了这样一句话:

      // Return an object that defines its own operator[] that will access the data.
      // The temp object is very trivial and just allows access to the data via 
      // operator[]
      VectorDeque2D_Inner_Set<T> operator[](unsigned int first_index) { 
        return VectorDeque2D_Inner_Set<T>(*this, first_index);
      }
    

    那是干什么用的?它是否以某种方式增加了这个操作符的值,如果是,为什么??


    编辑1
    以下是完整的列表,以获取更多信息。函数位于类的底部。注意,我将变量从x重命名为index,并重命名了模板化的内部类。我忘了将typecast放到模板化的内部类中,这是我在这次更新中添加的。

    现在有什么想法吗?

    template <typename T>
    class Container
    {
    private:
        // ...
    
    
    public:
    
        // Proxy object used to provide the second brackets
        template <typename T>
        class OperatorBracketHelper
        {
            Container<T> & parent;
            size_t firstIndex;
        public:
            OperatorBracketHelper(Container<T> & Parent, size_t FirstIndex) : parent(Parent), firstIndex(FirstIndex) {}
    
            // This is the method called for the "second brackets"
            T & operator[](size_t SecondIndex)
            {
                // Call the parent GetElement method which will actually retrieve the element
                return parent.GetElement(firstIndex, SecondIndex);
            }
    
        }
    
        // This is the method called for the "first brackets"
        OperatorBracketHelper<T> operator[](size_t FirstIndex)
        {
            // Return a proxy object that "knows" to which container it has to ask the element
            // and which is the first index (specified in this call)
            return OperatorBracketHelper<T>(*this, FirstIndex);
        }
    
        T & GetElement(size_t FirstIndex, size_t SecondIndex)
        {
            // Here the actual element retrieval is done
            // ...
        }
    }
    
    3 回复  |  直到 14 年前
        1
  •  4
  •   Buhake Sindi Tesnep    14 年前

    这个 this 关键字基本上是指向它当前正在使用的对象的指针引用。在C++中, 是指针,所以要取消引用它,请使用 *this

    所以,这个代码,

    return VectorDeque2D_Inner_Set<T>(*this, index);
    

    这种方法,

     // This is the method called for the "first brackets"
        OperatorBracketHelper<T> operator[](size_t FirstIndex)
        {
            // Return a proxy object that "knows" to which container it has to ask the element
            // and which is the first index (specified in this call)
            return OperatorBracketHelper<T>(*this, FirstIndex);
        }
    

    刚刚通过了一个取消引用的 self OperatorBracketHelper 因为它需要一个 Container& 作为参数。

        2
  •  5
  •   Randolpho    14 年前

    * 运算符取消引用 this 指针。这是必要的,因为要调用的方法(构造函数 OperatorBracketHelper(Container<T> & Parent, size_t FirstIndex) )需要引用而不是指针。

        3
  •  1
  •   pm100    14 年前

    它创建一个OpBracketHelper实例,引用当前容器作为其父成员(*它将容器对象的引用传递给构造函数)

    我唯一关心的是容器和helper对象的生命周期。我很想使用shared\u ptr而不是引用