Friend function can't access the private variables

84 Views Asked by At

I am trying to overload the << operator to display a matrix, but it says that none of my private members can be accessed.

In my header file, I have:

friend ostream& operator<<(ostream& os, const matrix& out);

and for my private members I have:

private:
int p_rowSize;
int p_rowSize;
vector<vector<double> > p_matrix;

In my implementation file, I have the following code, and am unsure how I am supposed to get it to work:

ostream& operator<<(ostream& os, const matrix& out)
{
    for (int i = 0; i < p_rowSize; i++)
    {
        for (int j = 0; j < p_colSize; j++)
        {
            cout << "[" << p_matrix[i][j] << "] ";
        }
        cout << endl;
    }
}

It is telling me that p_colSize, p_rowSize, and p_matrix are all undefined here, but not in any other function that I've written.

1

There are 1 best solutions below

1
On BEST ANSWER

A friend function has access to the data members, but since it's still a free function (rather than a member function) you need to specify which object you're accessing using out.p_rowSize, etc.

ostream& operator<<(ostream& os, const matrix& out)
{
    for (int i = 0; i < out.p_rowSize; i++)
    {
        for (int j = 0; j < out.p_colSize; j++)
        {
            os << "[" << out.p_matrix[i][j] << "] ";
        }
        os << endl;
    }
    return os;
}

Some notes:

  1. You should output to os, not cout.
  2. You forgot to return a value from the function, so I added return os; for you.