访问struct本身的运算符

时间:2016-03-10 15:40:11

标签: c++ struct operators

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

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

1 个答案:

答案 0 :(得分:8)

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,并且您的函数应该返回float

相关问题