mardi 27 février 2018

C++ Overloading operator- (unary minus) as member function? [duplicate]

This question already has an answer here:

I have implemented a unary minus operator as a non-member function.

template<typename T>
vector3<T> operator-(const vector3<T> &v)
{
    //return vector3<T>(-v._x_, -v._y_, -v._z_);
    return vector3<T>(-v.GetX(), -v.GetY(), -v.GetZ());
}

This implementation looks out of place compared to the other functions I have written as the variables _x_,_y_ and _z_ are private, and therefore I have to use the Get methods to access the member variables.

I could declare this function as a friend. However this does not seem like a particularly good solution.

Is it possible to implement unary minus as a member function, thereby being able to access the members without the Get methods? It seems to me that such a thing would not make sense, becuase as this is a unary operator, what would the argument be? Would it simply have to be empty?

Aucun commentaire:

Enregistrer un commentaire