Search code examples
c++templatesfile-iomultidimensional-arrayfriend

invalid use of non-static data member error with template friend functions c++


#include <cassert>
#include <iostream>
#include <iostream>
#include <fstream>
#include <string> 
#include <iomanip>

using namespace std;

template <class T> class Matrix;

template <class T>
class Matrix
{
 public:

  friend istream& operator>>(istream& inStream,Matrix& other) 
 {
     string line ;
    T x ;
    unsigned _rows = 0 , _cols = 0 ;

    while(inStream.good())
    {
        while(getline(inStream,line))
        {
            istringstream streamA(line) ;
            _cols = 0;
            while(streamA >> x)
            {
                matrix[_rows][_cols] = x ;
                _cols++ ;
            }
            _rows++ ;
        }
    }
    return inStream ;
 }

  Matrix(unsigned r, unsigned c);
  Matrix(const Matrix<T>& rhs);
  ~Matrix();
  const Matrix operator=(const Matrix& other);

 void output() const ;

  // Matrix mathematical operations: insert overloaded operator signatures

  // Access the individual elements of a matrix: insert overloaded operator signatures

  // Getters:
  unsigned getRows() const; // Return number of rows
  unsigned getCols() const; // Return number of columns

 private:
  Matrix();

  T ** matrix; // the matrix array
  unsigned rows; // # rows
  unsigned cols; // # columns 

Above is my .h file. I am trying to overload the >> operator. in the "friend istream& operator>>(istream& inStream,Matrix& other)" function I am trying to load data from a text file but i keep on getting a invalid use of non-static data membererror.


Solution

  • There is no implicit this in a friend function, so you can't just use non-static data members. You have to access the members of your Matrix using the proper name for it, for instance other.matrix.