在结构本身内部访问运算符

Accessing operator inside struct itself

我正在尝试访问结构本身内部的运算符,这可能吗?

struct st{
    float vd;
    float val(){
      return this[3]; //this dont work, is there a some way?
    }
    float operator[](size_t idx){
        return  vd*idx;
    }
};

this 是指向对象而不是对象本身的指针。如果要调用成员函数可以直接调用函数

float val(){
  return operator[](3);
}

或者您可以取消引用 this 并在实际对象上调用 []

float val(){
  return (*this)[3];
}

因为 this 是一个指针 return this[3]; 转换为 return (this + 3); 这意味着给我驻留地址 this + sizeof(st)*3 的对象这是一个无效的对象因为 this 不是数组。这是 UB 并且还会导致编译器错误,因为 this[3] 的类型是 st 并且您的函数应该 return 是 float.