1. 程式人生 > >今天看到的一個有趣面試題:return *this和return this有什麼區別?

今天看到的一個有趣面試題:return *this和return this有什麼區別?

      別跟我說, return *this返回當前物件, return this返回當前物件的地址(指向當前物件的指標)。

      正確答案為:return *this返回的是當前物件的克隆或者本身(若返回型別為A, 則是克隆, 若返回型別為A&, 則是本身 )。return this返回當前物件的地址(指向當前物件的指標), 下面我們來看看程式吧:

#include <iostream>
using namespace std;

class A
{
public:
	int x;
	A* get()
	{
		return this;
	}
};

int main()
{
	A a;
	a.x = 4;

	if(&a == a.get())
	{
		cout << "yes" << endl;
	}
	else
	{
		cout << "no" << endl;
	}

	return 0;
}
      結果為:yes

      再看:

#include <iostream>
using namespace std;

class A
{
public:
	int x;
	A get()
	{
		return *this; //返回當前物件的拷貝
	}
};

int main()
{
	A a;
	a.x = 4;

	if(a.x == a.get().x)
	{
		cout << a.x << endl;
	}
	else
	{
		cout << "no" << endl;
	}

	if(&a == &a.get())
	{
		cout << "yes" << endl;
	}
	else
	{
		cout << "no" << endl;
	}

	return 0;
}
     結果為:

4

no

     最後, 如果返回型別是A&, 那麼return *this返回的是當前物件本身(也就是其引用), 而非副本。