C++成员函数返回对象的引用

        在C++类的成员函数中,包含了一个隐含的this指针。一般情况下,并不会显示地使用this指针,即通过”this->XXX“来使用类的成员。但是在成员函数返回对该调用函数的对象的引用时,会显示的使用this。

为什么要返回调用该函数的对象的引用呢?C++ Primer 4里说用户希望能将几个操作连接成一个独立的表达式,例如下面:

myScreen.move(4,0);
myScreen.set('#');

用户希望直接写成这个样子:

myScreen.move(4,0).set('#');

由于成员函数中this为指向该对象的指针,那么我们返回时需要:

return *this;

这时,我们在调用这个成员函数的过程中,传递来的this指针和最后返回的*this引用都是指向调用该函数的对象。所以上面讲几个表达式连接起来可以实现分开的功能。

要牢记这时的函数类型,即返回值类型必须为引用类型,否则的话函数返回的对象是一个新的对象,在连接操作中,第一个操作是对this所指对象的操作,第二操作则是对以一个操作返回的新对象进行,不再是一开始this所指向对象了。所以这时,仅会实现第一个操作。例如:

我们定义了一个test类,test.h文件:

class test
{
public:test(int a) { x = a; }test minus1(int a);test& minus2(int a);int x;
};

test.cpp文件:

#include "test.h"
#include <iostream>
using namespace std;test test::minus1(int a)
{x = x - a;cout<<"minus1 is called, x= "<<x<<endl;return *this;
}test& test::minus2(int a)
{x = x - a;cout<<"minus2 is called, x= "<<x<<endl;return *this;
}

我们这样调用:

#include "test.h"
#include <stdlib.h>
#include <iostream>
using namespace std;int main()
{test t1(5),t2(5);t1.minus1(1).minus1(1).minus1(1).minus1(1);cout<<"t1.x = "<<t1.x<<endl;t2.minus2(1).minus2(1).minus2(1).minus2(1);cout<<"t2.x = "<<t2.x<<endl;system("PAUSE");
}

最后结果为: