本文讨论的是在C++的类相关知识中,关于函数的返回值为 *this 与 this 的情况。
return *this返回的是当前对象的克隆或者本身(若返回类型为A, 则是克隆, 若返回类型为A&, 则是本身 )。return this返回当前对象的地址(指向当前对象的指针), 下面我们来看看程序吧:
#define _CRT_SECURE_NO_WARNINGS
#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 << "地址" << endl;
}
else
{
cout << "非地址" << endl;
}
return 0;
}
控制台显示:地址
这说明get()方法中的return this,返回的是当前对象的地址
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class A
{
public:
int x;
A() {
x = 0;
}
//这里写了一个拷贝构造函数,所以得再提供一个构造函数
A(const A &a) {
x = a.x;
printf("copy constructor is called\n");
}
//* 如果显示的写了一个普通的构造函数,会隐藏默认的无参构造函数
//*如果显示的写了一个拷贝构造函数,会隐藏默认的无参构造函数和默认构造函数
//* 如果显示的写了一个析构函数,会隐藏默认的析构函数
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 << "地址" << endl;
}
else
{
cout << "不是地址" << endl;
}
return 0;
}
控制台显示:
copy constructor is called
4
copy constructor is called
不是地址
这说明get()方法中的return *this在程序运行过程中返回的不是地址,而是当前对象的一个拷贝(因为调用了拷贝构造函数)
如果将程序返回值改为A&,代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class A
{
public:
int x;
A() {
x = 0;
}
//这里写了一个拷贝构造函数,所以得再提供一个构造函数
A(const A &a) {
x = a.x;
printf("copy constructor is called\n");
}
//* 如果显示的写了一个普通的构造函数,会隐藏默认的无参构造函数
//*如果显示的写了一个拷贝构造函数,会隐藏默认的无参构造函数和默认构造函数
//* 如果显示的写了一个析构函数,会隐藏默认的析构函数
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 << "地址" << endl;
}
else
{
cout << "不是地址" << endl;
}
return 0;
}
控制台显示:
4
不是地址
说明当返回类型为 A& 时,没有调用拷贝构造函数,返回的是当前对象本身(即引用),而不是拷贝出来的副本。