C++中return this与*this这两种不同的返回值形式

C++中return this与*this这两种不同的返回值形式

本文讨论的是在C++的类相关知识中,关于函数的返回值为 *this 与 this 的情况。

return *this返回的是当前对象的克隆或者本身(若返回类型为A, 则是克隆, 若返回类型为A&, 则是本身 )。return this返回当前对象的地址(指向当前对象的指针), 下面我们来看看程序吧:

#define _CRT_SECURE_NO_WARNINGS

#include

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

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

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& 时,没有调用拷贝构造函数,返回的是当前对象本身(即引用),而不是拷贝出来的副本。

// 相关文章

正义从哪里来(新版,得到近80万总订阅主理人熊逸颇具思辨张力的经典神作,公平正义比太阳还要有光辉!)
昔日网红女神Happy Polla 即将复出
365bet足彩论坛

昔日网红女神Happy Polla 即将复出

⌛ 07-11 ⚠️ 7965
保姆级教程:搭建自己的 Minecraft 服务器,跟好友一起玩!
365beat网页怎么打不开

保姆级教程:搭建自己的 Minecraft 服务器,跟好友一起玩!

⌛ 07-05 ⚠️ 2877