gpt4 book ai didi

c++ - 在 C++ 中使用 "This"指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:24:04 26 4
gpt4 key购买 nike

我一直在各种站点(例如 MSDN 手册)上阅读有关“this”指针的信息,并了解它的基本用途——返回您自己的对象的拷贝或使用它的指针进行返回/比较。

但是我遇到了这个声明:

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

那有什么作用?它是否会以某种方式增加 this 运算符,如果是,为什么??

(这来 self 在堆栈溢出时给出的示例,因此语法中可能存在错误。如果需要更大的 block ,请告诉我,我可以粘贴更多代码。)


编辑 1
这是完整的 list ,以获取更多信息。该函数靠近类的底部。注意我将变量从 x 重命名为 index 并重命名了模板化内部类。我忘记将类型转换放入我在本次更新中添加的模板化内部类。

现在有什么想法吗?

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
// ...
}
}

最佳答案

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

这是失败模式吗?我不知道。它在我的本能水平上闻起来,但我找不到任何直接错误的地方。

关于c++ - 在 C++ 中使用 "This"指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3781049/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com