gpt4 book ai didi

c++ - this[i] 在没有重载的情况下在 C++ 中是什么意思

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:26 25 4
gpt4 key购买 nike

这是来自 WebKit 的代码:

class ExecState : public Register 
{
JSValue calleeAsValue() const { return this[JSStack::Callee].jsValue(); }
...
}

JSStack::CalleeconstOperator[] 没有在 ExecState 中重载注册,

那么 this[JSStack::Callee] 在 c++ 中的语法是什么?

最佳答案

好吧,this 是一个指向 ExecState 的指针,使用带有指针的下标运算符可以使其表现得就像一个数组。也就是说,表达式 this[JSStack::Callee] 访问一个对象,该对象距离 thisJSStack::Callee 个元素。当然,这只有在元素是 ExecState 对象数组的成员时才可能起作用。

下面是使用此“功能”的快速独立演示。一般来说,我建议不要使用它,但可能有非常具体的需求,已知在数组中使用了一个类型并且访问是可行的。例如,如果类型是在本地定义的,那么所有已知的用途都可能是已知的(不过,我会添加一条说明该假设的注释)。

#include <iostream>

class foo {
int d_value;
public:
foo(int i): d_value(i) {}
int get(int i) const { return this[i].d_value; }
};

template <typename T, int Size>
int size(T(&)[Size]) { return Size; }

int main()
{
foo f[] = { 9, 1, 8, 2, 7, 3, 6, 4, 5 };
for (int i=0; i < size(f) - 2; ++i) {
std::cout << "f[" << i << "].get(2)=" << f[i].get(2) << '\n';
}
}

关于c++ - this[i] 在没有重载的情况下在 C++ 中是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26574228/

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