为模板矩阵实现多个订阅操作符(operator())

implementing multiple subscription operators for template matrix (operator())

我收到了实现通用矩阵的练习 class。 其中一项任务如下:"Overload operator() which gets parameterse (unsigned int, unsigned int) twice, once as const and once as a non-const.".

现在,经过大量搜索,我明白他们的签名应该是这样的:

    T operator()(unsigned int rows, unsigned int colls) const; //cout << "A" << endl;
    T & operator()(unsigned int rows, unsigned int colls); //cout << "B" << endl;

但是,无论我尝试用哪种方式称呼它们,都只会调用第二个:

    int main()
    {
        Matrix<int> mat(2, 3);
        mat(1, 1) = 3;
        int i= (9 + mat(1, 1)) ;
        i = mat(2, 1);
        cout << i << endl;
        if (i == mat(1, 2)) {}
        int j = Matrix<int>(2, 2)(1, 1); //calls constructor and then subscription.
    }

输出将是:

B
B
B
0
B
B

老师的要求很好 operator()。宇宙才有希望。

与其说这是一件 rvalue/lvalue 的事情,不如说它是 constant/non 常量。 方法定义末尾的 const 指出(编译器会做一个合理的级别检查它不会)调用该方法不会改变对象的状态。如果您希望能够在常量对象上调用方法,则绝对有必要。

如果您将以下函数添加到您的测试代码中:

void consttest(Matrix<int> &mat, const Matrix<int> &cmat)
{
    mat(1,1) =4;
    cmat(1,1) =4;
}

并这样称呼它:

consttest(mat, mat);

您会看到很好的 rvalue/lvalue 东西在起作用。可悲的是,你不会看到你的 const operator() 被调用,因为它不会编译。以它自己的方式进行的相当不错的测试,该方法很好地防止了错误,但是对功能更有用的测试是:

void consttest(Matrix<int> &mat, const Matrix<int> &cmat)
{
    std::cout << mat(1,2) << std::endl;
    std::cout << cmat(1,2) << std::endl;
}

顺便说一句,这里有一段关于左值和右值的精彩对话:What are rvalues, lvalues, xvalues, glvalues, and prvalues?