C++ ()运算符重载c++;

C++ ()运算符重载c++;,c++,class,operator-overloading,C++,Class,Operator Overloading,我对重载运算符()的调用有些困惑 类矩阵中有两个函数: float operator()(int, int) const; // suppose I call this function rvalue float& operator()(int, int); // and lvalue 现在,当我在main中调用它们时,以这种方式: Matrix M2(3, 2); M2(0, 0) = 1; // here lvalue should be called int c=M2(0,0);

我对重载运算符()的调用有些困惑

类矩阵中有两个函数:

float operator()(int, int) const; // suppose I call this function rvalue
float& operator()(int, int); // and lvalue
现在,当我在main中调用它们时,以这种方式:

Matrix M2(3, 2);
M2(0, 0) = 1; // here lvalue should be called
int c=M2(0,0); // and here rvalue
但在这两种情况下,它都调用左值函数。为什么

如果我注释左值函数,我会

int c=M2(0,0); // now it calls rvalue function
但在两个函数都存在的情况下,它调用左值函数。为什么?


希望,我的问题很清楚

类类型的右值不是您可能认为的
const
const
重载将在
const
限定的对象上调用,但在其他情况下,将优先选择最不限定的版本

您可以使用ref限定符重载(仅限C++11):


我想知道为什么这并不含糊您的术语不正确-通过
const
类型的表达式访问的对象调用了
const
成员函数。这与左值或右值无关。在您的示例代码中,没有一个表达式是
const
,因此不调用该版本。
M2
不是
const
,因此非const运算符更匹配。明白了,谢谢大家。
float operator()(int, int) && const; // called when object is rvalue 
float& operator()(int, int) &;       // called when object is lvalue