当前位置: 代码迷 >> C++ >> 为何有些运算符的重载返回类型后要返回&
  详细解决方案

为何有些运算符的重载返回类型后要返回&

热度:2887   发布时间:2013-02-26 00:00:00.0
为什么有些运算符的重载返回类型后要返回&
比如书上的代码重载=、+=、-=、<<时返回类型后都加了&
发现所有要加&的结尾都是return *this;以及流运算符
但是我写了一个矩阵类
class Matrix
{
private:
int row,col;
double* pt;
public:
//构造函数
Matrix();
Matrix(int,int,double*);
Matrix(const Matrix&);
//运算函数
Matrix operator=(const Matrix&);
Matrix operator+(const Matrix&);
Matrix operator-(const Matrix&);
Matrix operator*(const Matrix&);
friend double delta(const Matrix&);
Matrix inv();
Matrix adj();
void display();
~Matrix();
};

Matrix Matrix::operator=(const Matrix& m)
{
row=m.row;
col=m.col;
pt=new double[m.col*m.row];
for(int i=0;i<row*col;i++)
pt[i]=m.pt[i];
return *this;
}

#include "stdafx.h"
#include "matrix.h"
#include <iostream>
using namespace std;
int main()
{
double p[6]={1,2,3,4,5,6};
Matrix m(2,3,p);
Matrix n=m*m.adj();
n.display();
return 0;
}

我也是返回*this但是前面没用&一样成功了,求问用&的意义在哪。

------解决方案--------------------------------------------------------
返回Matrix &的话直接返回的就是return的那个Matrix。返回Matrix的话,返回的是return的那个Matrix的临时副本(GCC下是个只读的临时副本)。
------解决方案--------------------------------------------------------
& 表示的是引用啊,那么返回的时候就不用多一个临时对象的创建和析构了,于是提高了效率。
再则,如果需要修改返回的对象值,就必须返回引用,因为c++ 不允许对一个临时对象做修改。
其次,IO流的对象不允许复制和赋值,所以必须返回引用。
  相关解决方案