-1

My code:

matrix.h

#include <iostream>

class Matrix {
private:
    int row;
    int col;
    int **array;

public:
    Matrix();
    friend std::ostream& operator<<(ostream& output, const Matrix& m);
};

matrix.cpp

#include "matrix.h"
#include <iostream>

Matrix::Matrix()
{
    row = 3;
    col = 4;

    array = new int*[row];

    for (int i = 0; i < row; ++i)
    {
        array[i] = new int[col];
    }

    for (int i = 0; i < row; ++i)
    {
        for (int j = 0; j < col; ++j)
        {
            array[i][j] = 0;
        }
    }
}

std::ostream& operator<<(std::ostream& output, const Matrix& m)
{
    output << "\nDisplay elements of Matrix: " << std::endl;

    for (int i = 0; i < m.row; ++i)
    {
        for (int j = 0; j < m.col; ++j)
        {
            output << m.array[i][j] << " ";
        }
        output << std::endl;
    }

    return output;
}

main.cpp

#include "matrix.h"
#include <iostream>
using namespace std;

int main()
{
    Matrix a;
    cout << "Matrix a: " << a << endl;

    system("pause");
    return 0;
}

Error:

  1. member "Matrix::row" (declared at line 3 matrix.h") is inaccessible
  2. member "Matrix::col" (declared at line 3 matrix.h") is inaccessible
  3. member "Matrix::array" (declared at line 3 matrix.h") is inaccessible
  4. binary '<<' : no operator found which takes a right-hand operand of type 'Matrix'
  5. 'ostream': ambiguous symbol
  6. 'istream': ambiguous symbol

What am I doing wrong? :(

**Edited: I've editted the question to give a MCVE example like Barry suggested, and also removed using namespace std like Slava recommended. I'm still getting the same error.

2 Answers2

2

Now that you have a complete example, you're missing std:: here:

friend std::ostream& operator<<(ostream& output, const Matrix& m);
                              ^^^

Add it and everything compiles fine:

friend std::ostream& operator<<(std::ostream& output, const Matrix& m);
Barry
  • 286,269
  • 29
  • 621
  • 977
1

What am I doing wrong? :(

It is a bad practice to put statement using namespace std; into header, and there is a reason for that. According to this:

'ostream': ambiguous symbol 'istream': ambiguous symbol

You have istream and ostream declared in global namespace somewhere. Follow good practice, it is not so difficult to type std::

Slava
  • 43,454
  • 1
  • 47
  • 90
  • Okay, here's the new edited code.. I've followed your suggestion. Not sure if I'm doing it right though cz I'm new to c++ and I've always used using namespace std in all my programs.. I can still use using namespace std in my Main.cpp right? – ChewingSomething Sep 25 '15 at 15:58
  • 1
    @ChewingSomething show exact errors, not your interpretations – Slava Sep 25 '15 at 16:02