I have a Matrix
class and a Vector
class, which have declarations in header files and definitions in their own source files, and I want to overload the *
operator two ways. I would like to be able to write expressions like
Matrix m1, m2, m3;
...
m3 = m1 * m2;
and also expressions like
Vector v1, v2;
Matrix m;
...
v2 = m * v1;
The first overloading seems easy, as it's simply a member function of the Matrix class:
class Matrix {
public:
Matrix operator*(Matrix &m)
}
excerpt from matrix.hpp
.
However, I am not sure where/how to declare/define the other overloading of the operator. I had thought that I needed a friend
function to be able to access the private members of both classes, so I tried the following declaration in the Vector
class:
class Vector {
public:
friend Vector operator*(const Matrix &m, const Vector &v);
}
excerpt from vector.hpp
.
This seemed to follow the pattern I found in this question in the accepted answer, although it is overloading of a different operator. However, when I try to compile my source files that define the overloading, I get errors because it can't access the private members of the Matrix
class.
Most of the other questions and answers I've seen are attempting to overload a binary operator to act on two instances of the same class, like my first example, and in fact my linked answer is THE ONLY place I've seen something similar to what I'm doing.
So how should this be defined?
EDIT:
The accepted answer to the possible duplicate states "Make it friend
ONLY when it needs to access private members." I do need to access private members, but my compiler tells me that even after making it friend
I still can't access the private members of Matrix
.