访问struct本身的运算符

use*_*324 3 c++ struct operators

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

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;
    }
};
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 8

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

float val(){
  return operator[](3);
}
Run Code Online (Sandbox Code Playgroud)

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

float val(){
  return (*this)[3];
}
Run Code Online (Sandbox Code Playgroud)

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