Search code examples
c++operator-overloadingoverloading

Bug on a custom C++ class


I need help on finding the problem using a custom c++ class to manage 3D positions. Here is the relevant code from the class

  Punto operator+(Punto p){
    return Punto(this->x + p.x, this->y + p.y, this->z + p.z);
  }

  Punto operator+(Punto *p){
    return Punto(this->x + p->x, this->y + p->y, this->z + p->z);
  }

  Punto operator-(Punto p){
    return Punto(this->x - p.x, this->y - p.y, this->z - p.z);
  }

  Punto operator-(Punto *p){
    return Punto(this->x - p->x, this->y - p->y, this->z - p->z);
  }

  Punto *operator=(Punto p){
    this->x = p.x;
    this->y = p.y;
    this->z = p.z;
    return this;
  }

  Punto *operator=(Punto *p){
    this->x = p->x;
    this->y = p->y;
    this->z = p->z;
    return this;
  }

I'm using it here like this:

p = fem->elementoFrontera[i]->nodo[0] - fem->elementoFrontera[i]->nodo[1];

Where nodo[i] is a Punto*, and it compiles fine, but when I try to do:

p = fem->elementoFrontera[i]->nodo[0] + fem->elementoFrontera[i]->nodo[1];

The compiler says:

In member function void mdTOT::pintarElementosFrontera()': error: invalid operands of types Punto*' and Punto*' to binary operator+'


Solution

  • The first one compiles fine because you can subtract pointers in C/C++, but not add pointers. But in any case it doesn't do what you need - it doesn't use your overloaded operator. Since your operators are defined in a class, you need to operate on class instances, not on pointers. So, change to something like

    Punto p = *(fem->elementoFrontera[i]->nodo[0]) + *(fem->elementoFrontera[i]->nodo[1]);
    

    Another thing - you should use class references, not values, in operator definition. E.g.

     Punto& operator+(const Punto& p) {
    

    EDIT. To simplify the code, you can create an accessor function, like this:

    const Punto& NodoRef(int i, int j) {
      return *(fem->elementoFronteria[i]->Nodo[j]);
    }
    

    and then your code becomes as clean as

    p = NodoRef(i,0) + NodoRef(i,1);
    

    The NodoRef may be defined in your fem class, or outside. Just make sure the object fem is alive in the scope where you use the NodoRef.