Reputation: 2458
I am working on an assignment that introduces me to operator overloading. I have to overload some binary operators as member functions and also as friend functions. My member function that overloads the "+" operator works fine but my friend function that overloads the "-" operator seems to have trouble finding data that the member function is able to use.
class def:
class matrix
{
friend ostream& operator << (ostream&, const matrix&);
friend bool operator == (const matrix &, const matrix &);
friend matrix operator - (const matrix &, const matrix &);
private:
int size;
int range;
int array[10][10];
public:
matrix(int);
matrix(int, int);
bool operator != (const matrix &) const;
matrix operator + (const matrix &) const;
const matrix & operator = (const matrix &);
};
"+" overload:
matrix matrix::operator + (const matrix & a) const
{
matrix temp(size,range);
for (int i = 0; i < a.size; i++)
for (int j = 0; j < a.size; j++)
temp.array[i][j] = a.array[i][j] + array[i][j];
return temp;
}
"-" overload:
matrix operator - (const matrix & a, const matrix & b)
{
matrix temp(size, range);
for (int i = 0; i < a.size; i++)
for (int j = 0; j < a.size; j++)
temp.array[i][j] = a.array[i][j] - array[i][j];
return temp;
}
The error I am getting in the friend function is that size, range, and array are all undeclared. I am confused because I thought member and friend functions both had equal access to data in a class and I basically doing the same thing in both functions. Does anyone know what my issue may be?
Upvotes: 0
Views: 1635
Reputation: 16338
The friend operator is not part of the class. Thus, it does not know size
and range
and array
. You must use the objects a
and b
. It should be something like this:
matrix operator - (const matrix & a, const matrix & b)
{
if(a.size != b.size)
throw std::exception(...);
matrix temp(a.size, a.range);
for (int i = 0; i < a.size; i++)
for (int j = 0; j < a.size; j++)
temp.array[i][j] = a.array[i][j] - b.array[i][j];
return temp;
}
Upvotes: 5
Reputation: 22124
Though your friend function would be able to access the private data of the Objects, but this doesn't imply that the attributes are in the scope of that function. I mean, it wont act like a member function as you are expecting it to. You would need to provide the size from one of the objects that you are passing.
Upvotes: 0