Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing operator inside struct itself

I'm trying to access an operator inside the struct itself, is this possible?

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;
    }
};
like image 967
superbem Avatar asked Feb 03 '26 13:02

superbem


1 Answers

this is a pointer to the object not the object itself. If you want to call a member function you can call the function directly

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

or you can dereference this and call [] on the actual object.

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

Since this is a pointer return this[3]; translated to return (this + 3); which means give me the object that resides address of this + sizeof(st)*3 which is an invalid object since this is not an array. This is UB and will also cause a compiler error as the type of this[3] is a st and your function is supposed to return a float.

like image 60
NathanOliver Avatar answered Feb 05 '26 03:02

NathanOliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!