Search code examples
c++overloadingfriend

How come my friend functions can access public stuff?


Below are my code. I have 3 friend functions:

#include <iostream>
#ifndef   MATRIX_H
#define  MATRIX_H
class Matrix
    {
    friend Matrix operator++(Matrix&);
    friend Matrix operator--(Matrix&);
    friend ostream& operator<<(ostream&, Matrix&);
    private:
        int dim;
        int** mat;
    public:
        Matrix(int d);
        void set(int, int, int);
        int get(int, int);
        Matrix operator+(Matrix&);
        Matrix operator-(Matrix&);
        Matrix operator*(Matrix&);
        ~Matrix();
    };

Matrix operator++(Matrix &m)
    {
    for (int i = 0; i < m.dim; i++)
        {
        for (int j = 0; j < m.dim; j++)
            {
            int val = m.get(i,j);
            m.set(i,j,++val);
            }
        }
    return m;
    }

Matrix operator--(Matrix &m)
    {
    for (int i = 0; i < m.dim; i++)
        {
        for (int j = 0; j < m.dim; j++)
            {
            int val = m.get(i,j);
            m.set(i,j,--val);
            }
        }
    return m;
    }

ostream& operator<<(ostream &os, Matrix &m)
    {
    for (int i = 0; i < m.dim; i++)
        {
        for (int j = 0; j < m.dim; j++)
            {
            os << m.get(i,j) << ' ';
            }
        os<<endl;
        }
    return os;
    }

#endif

It's not complaining in either of them about "m.get(i,j)", which I believe is a public function...it's complaining about "m.dim", saying it's not accessible, in operator <<, but not in the first two. Why??


Solution

  • You simply forgot to prepend std:: before ostream in all locations.

    friend std::ostream& operator<<(std::ostream&, Matrix&);