I have the following class declared :
class MyVector {
private:
int *data;
unsigned int vector_size;
public:
MyVector();
MyVector(unsigned int n);
MyVector(unsigned int size, int *in_array=NULL);
MyVector(const MyVector& copy);
~MyVector();
void print();
// Assignment operator.
MyVector& operator=(const MyVector& v);
};
// Implementing operator overloading.
MyVector& operator*(const int &lhs, const MyVector &rhs);
MyVector& operator*(const MyVector &lhs, const MyVector &rhs);
I wish to implement an overloaded operator (*) so that I can use to multiply the objects of this class with a scalar (on the left hand side) or another object of the same type.
So, in execution, something like this :
// If all c, a, and b are of type MyVector.
c = (a * b);
And
// If c is of type MyVector.
c = (5 * c);
In implementation however I know I cannot access the private members of the class in this way. An alternative would be to use the friend
keyword, but wouldn't that be abusing its usage ?
If it helps, this is my implementation of one of the overloaded functions (scalar multiplication) :
MyVector& MyVector::operator*(const int &lhs, const MyVector &rhs) {
for (unsigned int i = 0; i < rhs.vector_size; i++) {
rhs.data[i] = rhs.data[i] * lhs;
}
return *rhs;
}