在成员函数内访问参数的类成员

时间:2019-05-30 19:25:43

标签: c++ function class protected

我正在写一些代码,这是我正在做的一个小项目的一部分,在我测试代码时,对我来说有些突出。我正在使用如下所示的类函数:

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。查看类定义,成员是私有的,那么我如何被允许访问它们?即使参数m作为const传递,由于nrows和ncols参数是受保护的,我是否不能(从参数)访问它们?我对为什么允许这样做感到困惑。

1 个答案:

答案 0 :(得分:3)

来自access specifiers at cppreference.com

  

该类的私人成员只能由该类的成员和朋友访问,无论这些成员是在相同实例还是在不同实例上:

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
};
相关问题