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

标签 c++ class operator-overloading

我对重载 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

但是在两个函数都存在的情况下,它调用左值函数。为什么?

希望,我的问题很清楚。

最佳答案

类类型的右值并不像您想象的那样constconst 重载将在 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/

相关文章:

C++ 模板和 header 分配

c++ - 如何将 argv 转换为 CreateProcess 的 lpCommandLine 参数?

c++ - 使用带有帧缓冲区的 RGBA32F 纹理抛出 INVALID_ENUM 错误

java - 两个相同的类可以序列化和反序列化吗?

c++ - 为什么ADL对运算符(operator)功能的行为不同于其他功能?

c++ - 隐式转换为 basic_istream/ifstream/ofstream 的 bool 在 Visual Studio 2013 中不起作用

c++ - 尝试在不使用 vector 的情况下在 C++ 中创建同一类的许多对象

java - 将加载的类保存到文件

c++ - 为模板类重载运算符时的隐式转换

c++ - 通过模板化运算符重载将 std::complex<T> 乘以 double