【问题标题】:Accessing Class Members of an Argument within a Member Function在成员函数中访问参数的类成员
【发布时间】:2019-10-16 11:28:06
【问题描述】:

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

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

【问题讨论】:

  • 摆弄一些你在网上找到的代码不会帮助你学习语言,抓住a good c++ book
  • public = 每个人都可以访问; protected = 类和派生可以访问; private = 只能在同一个类中访问

标签: c++ function class protected


【解决方案1】:

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

【讨论】:

  • 感谢您的回复。我已经有一段时间没有真正参与过课程了,所以这对我来说是一个很好的复习。谢谢你的回答。
猜你喜欢
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
  • 2013-12-26
  • 2014-07-29
  • 1970-01-01
  • 2017-09-19
  • 2022-01-10
  • 1970-01-01
相关资源
最近更新 更多