简体   繁体   English

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

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

I'm writing up some code as part of a little project I'm working on, and something stood out to me as I was testing my code. 我正在编写一些代码作为我正在进行的一个小项目的一部分,当我测试我的代码时,有些东西对我很有帮助。 I'm working with a class function shown below: 我正在使用如下所示的类函数:

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

Below, paying attention to the madd function, I've written it out in another file shown below: 下面,注意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;
}

I suppose you can guess that it does matrix addition. 我想你可以猜到它会添加矩阵。 To be honest, I found some code online, and I'm just trying to modify it for my own use, so this function wasn't completely written by me. 说实话,我在网上发现了一些代码,我只是想把它修改为自己使用,所以这个功能并不是我完全写的。 I managed to compile this, and after a small test, it worked correctly, but what I'm confused by is how in the function I was able to call m.ncols and m.nrows. 我设法编译了这个,经过一个小测试后,它工作正常,但我感到困惑的是我在函数中如何调用m.ncols和m.nrows。 Looking at the class definition, the members are private, so how am I allowed to access them? 查看类定义,成员是私有的,所以如何允许访问它们? Even though the argument m is passed as a const, since the nrows and ncols parameters are protected, shouldn't I NOT be able to access them (from the argument)? 即使参数m作为const传递,由于nrows和ncols参数受到保护,我应该能够访问它们(从参数中)? I'm confused as to why this is allowed. 我很困惑为什么这是允许的。

From access specifiers at cppreference.com 来自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
};

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

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