簡體   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