我对重载 operator() 的调用有些困惑。
类矩阵中有两个函数:
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
合格的对象上调用,但除此之外,将优先使用最不合格的版本。
你可以做的是用引用限定符重载(仅限 C++11):
float operator()(int, int) && const; // called when object is rvalue
float& operator()(int, int) &; // called when object is lvalue
关于c++ - () 运算符重载 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22862735/