这[i]在C ++中的含义是什么,没有重载

what's the meaning of this[i] in c++ without overloading

本文关键字:是什么 重载      更新时间:2023-10-16

这是WebKit的代码:

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

JSStack::CalleeconstOperator[]ExecStateRegister中未过载,

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

好吧,this是指向ExecState的指针,将下标运算符与指针一起使用会使其表现得像一个数组。也就是说,表达式this[JSStack::Callee]访问与this相距JSStack::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';
    }
}