成员无法使用好友功能访问

Members inaccessible with friend function

本文关键字:好友 功能 访问 成员      更新时间:2023-10-16

我收到一个无法解释的错误。这是我的头文件:

#include <iostream>
using namespace std;
namespace project
{
#ifndef MATRIX_H
#define MATRIX_H
typedef int* IntArrayPtr;
class Matrix
{
public:
    friend ostream& operator<<(ostream& out, const Matrix& object);
    friend istream& operator>>(istream& in, Matrix& theArray);
    //Default Constructor
    Matrix();
    Matrix(int max_number_rows, int max_number_cols, int intial_value);
    //Destructor
    ~Matrix();
    //Copy Constructor
    Matrix(const Matrix& right_side);
    //Assignment Operator
    Matrix& operator=(const Matrix& right_side);
    void Clear();
    int Rows();
    int Columns();
    bool GetCell(int x,int y, int& val);
    bool SetCell(int x,int y, int val);
    //void Debug(ostream& out);
private:
    int initialVal;
    int rows;
    int cols;
    IntArrayPtr *m;
};
#endif
}

这是我的定义:

ostream& operator<<(ostream& out, const Matrix& object)
{
    for(int r = 0; r < object.rows; r++)
    {
        for(int c = 0; c < object.cols; c++)
        {
            out << object.m[r][c] << " ";
        }
        out << endl;
    }
    return out;
}

它给了我一个错误,即 Matrix.h 成员无法访问,但我明确指出它们是好友功能。

这些函数定义位于何处?friend声明将名称注入namespace project。如果函数未在该命名空间中定义,则它们是不同的函数,而不是友元。

您的函数实现也应该驻留在 project 命名空间中 - 仅仅声明您正在使用它是不够的,如果您不这样指定它,函数本身就是"全局",然后无法访问成员,因为它在错误的命名空间范围内是好友。

使用此修复程序可以正常编译。

否则不编译。

尝试在 Matrix 类之外定义两个友元函数。

喜欢:

#include <iostream>
using namespace std;
namespace project
{
#ifndef MATRIX_H
#define MATRIX_H
typedef int* IntArrayPtr;
class Matrix
{
public:
    //Default Constructor
    Matrix();
    Matrix(int max_number_rows, int max_number_cols, int intial_value);
    //Destructor
    ~Matrix();
    //Copy Constructor
    Matrix(const Matrix& right_side);
    //Assignment Operator
    Matrix& operator=(const Matrix& right_side);
    void Clear();
    int Rows();
    int Columns();
    bool GetCell(int x,int y, int& val);
    bool SetCell(int x,int y, int val);
    //void Debug(ostream& out);
private:
    int initialVal;
    int rows;
    int cols;
    IntArrayPtr *m;
};
 ostream& operator<<(ostream& out, const Matrix& object);
 istream& operator>>(istream& in, Matrix& theArray);
#endif
}