在成员函数中访问参数的 Class 个成员

Accessing Class Members of an Argument within a Member Function

我正在编写一些代码作为我正在从事的一个小项目的一部分,在我测试我的代码时,一些事情对我来说很突出。我正在使用如下所示的 class 函数:

class Matrix{
    public:
        //Constructors
        Matrix();                   //EMPTY Matrix
        Matrix(int, int);           //Matrix WITH ROW AND COL
        Matrix(const Matrix &);     //Copy a matrix to this one
        ~Matrix();                  //Destructor

        //Matrix operations involving the matrix in question
        Matrix madd(Matrix const &m) const; // Matrix addition

    private:
        double **array; //vector<vector<double>> array;
        int nrows;
        int ncols;
        int ncell;
};

下面,注意madd函数,我已经写在另一个文件中了,如下所示:

Matrix Matrix::madd(Matrix const &m) const{
    assert(nrows==m.nrows && ncols==m.ncols);

    Matrix result(nrows,ncols);
    int i,j;

    for (i=0 ; i<nrows ; i++)
        for (j=0 ; j<ncols ; j++)
            result.array[i][j] = array[i][j] + m.array[i][j];

    return result;
}

我想你能猜到它做的是矩阵加法。老实说,我在网上找了一些代码,我只是想修改它以供自己使用,所以这个功能并不是我完全写的。我设法编译了它,经过一个小测试后,它工作正常,但我感到困惑的是我如何在函数中调用 m.ncols 和 m.nrows。查看 class 定义,成员是私有的,那么如何允许我访问它们?即使参数 m 作为常量传递,由于 nrows 和 ncols 参数受到保护,我不应该 NOT 能够访问它们(从参数)吗?我很困惑为什么允许这样做。

来自access specifiers at cppreference.com

A private member of a class can only be accessed by the members and friends of that class, regardless of whether the members are on the same or different instances:

class S {
private:
    int n; // S::n is private
public:
    S() : n(10) {} // this->n is accessible in S::S
    S(const S& other) : n(other.n) {} // other.n is accessible in S::S
};