Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

c++ - My ostream and istream friend function can't access private class members

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 << "
Display 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...