繁体   English   中英

访问成员函数中的参数的类成员

[英]Accessing Class Members of an Argument within a Member Function

我正在编写一些代码作为我正在进行的一个小项目的一部分,当我测试我的代码时,有些东西对我很有帮助。 我正在使用如下所示的类函数:

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参数受到保护,我应该能够访问它们(从参数中)? 我很困惑为什么这是允许的。

来自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
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM