c++ - 使用引用和指针对大对象进行运算符重载

标签 c++ operator-overloading

在《The C++ Programming Language》一书中,作者给出了如下例子和几个主张。

class   Matrix {
   double  m[4][4];
   public:
      Matrix( );
      friend Matrix operator+(const  Matrix&, const Matrix&)
};

Matrix  operator+(const  Matrix& arg1, const Matrix& arg2)
{  
  Matrix sum;
  for (int i=0; i<4; i++)
  sum.m[i][j ]=arg1.m[i][j]+arg2.m[i][j];
  return sum;
 }

书中声称

references allow the use of expressions involving the usual arithmetic operators for large objects without excessive copying. Pointers cannot be used because it is not possible to redefine the meaning of an operator applied to a pointer.

我不明白上述说法中的“过度复制”指的是什么。对于“不能使用指针,因为不可能重新定义应用于指针的运算符的含义”的说法,我完全迷失了。感谢您的解释。

最佳答案

如果operator+相反被声明为按值获取其操作数,例如,

Matrix operator+(Matrix arg1, Matrix arg2)

然后复制arg1arg2必须将其传递给函数。一个简单的矩阵加法,例如,

Matrix x, y;
x + y;

将需要 x 的拷贝和 y被制造;实际上,您最终不得不复制 32 double s,虽然在这种情况下不是非常昂贵,但也不是特别便宜。当您通过引用获取参数时,无需复制。

请注意,某些运算符重载必须通过引用获取其参数。作为一个常见的例子,考虑 <<流插入运算符:它必须取其 std::istream通过引用操作数,因为不可能复制流。


不能使用指针,因为不能为指针重载运算符:每个运算符重载的至少一个操作数必须是类或枚举类型。即使你可以使用指针,语法也会很尴尬;而不是使用 x + y如上所示,您需要使用 &x + &y .

关于c++ - 使用引用和指针对大对象进行运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5208896/

相关文章:

c++ - 如何使用 gsl 在 cholesky 中打印下矩阵?

c++ - 这是三规则背后的正确逻辑吗?

c# - Unity3D,如何为运算符编写扩展方法?

c++ - 如何在C++中将不同模板类型的对象相乘

C++ 运算符重载和保护字段

C++,表达式不能是函数

c++ - 如何编译使用shared_ptr的程序?

c++ - 如果 + 运算符重载的第二个操作数在 C++ 中为零,如何返回第一个操作数?

import - Ada:导入不等式运算符 "/="

c++ - 如何在使用for循环和数组时更改为c代码