【问题标题】:How does parenthesis operator overlaoding work in C++?括号运算符重载如何在 C++ 中工作?
【发布时间】:2022-01-20 09:37:37
【问题描述】:

我有以下代码:

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

我想知道以下行如何将4.5 分配给m_data[1][2]。

matrix(1, 2) = 4.5;

其实double&amp; operator()(int row, int col)函数内部并没有赋值。它只有return m_data[row][col]; 语句。它不应该只返回m_data[1][2] 的值吗?在这种情况下,默认为0。

【问题讨论】:

  • 它返回一个double&amp;,可以用内置的operator=(double)分配给它
  • 您知道值 (double) 和引用 (double&amp;) 之间的区别吗?
  • 你知道double&amp; x = matrix(1,2); x = 4.5; 做那个任务吗?
  • 标题与问题正文中表达的误解不符。

标签: c++ c++11 operator-overloading


【解决方案1】:

这个函数:

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

返回一个 double 变量的引用,而不仅仅是一个值。

matrix(1, 2) = 4.5;

matrix(1, 2) 返回该变量的引用,并为该引用分配一个值,即4.5

【讨论】:

    猜你喜欢
    • 2010-09-22
    • 1970-01-01
    • 2017-08-15
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    相关资源
    最近更新 更多