简体   繁体   English

括号运算符在 C++ 中如何工作?

[英]How does parenthesis operator overlaoding work in C++?

I've following code:我有以下代码:

#include <iostream>
#include <cassert>

class Matrix
{
private:
    double m_data[3][3]{};

public:
    double& operator()(int row, int col);
};

double& Matrix::operator()(int row, int col)
{
    assert(col >= 0 && col < 3);
    assert(row >= 0 && row < 3);

    return m_data[row][col];
}

int main()
{
    Matrix matrix;
    matrix(1, 2) = 4.5;
    std::cout << matrix(1, 2) << '\n';

    return 0;
}

I'm wondering how does following line assigns the 4.5 to m_data[1][2] .我想知道下一行如何将4.5分配给m_data[1][2]

matrix(1, 2) = 4.5;

Actually, there is no assignment inside the function double& operator()(int row, int col) .实际上, function double& operator()(int row, int col)内部没有赋值。 It has only return m_data[row][col];它只return m_data[row][col]; statement.陈述。 Shouldn't it just return value at m_data[1][2] .它不应该只返回m_data[1][2]的值。 In that case it would be 0 by default.在这种情况下,默认为0

This function:这个 function:

double& Matrix::operator()(int row, int col)

return a reference of a double variable, not just a value.返回一个double变量的引用,而不仅仅是一个值。

matrix(1, 2) = 4.5;

matrix(1, 2) returns a reference of that variable, and that reference get assigned a value, that is 4.5 matrix(1, 2)返回该变量的引用,并且该引用被分配一个值,即4.5

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

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