服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - 浅析C/C++ 中return *this和return this的区别

浅析C/C++ 中return *this和return this的区别

2021-08-03 13:55ZhuJD C/C++

return *this返回的是当前对象的克隆或者本身,return this返回当前对象的地址,下面通过本文给大家介绍C/C++ 中return *this和return this的区别,感兴趣的朋友一起看看吧

首先我们知道~

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Test
{
public:
 Test()
 {
  return this; //返回的当前对象的地址
 }
 Test&()
 {
  return *this; //返回的是当前对象本身
 }
 Test()
 {
  return *this; //返回的当前对象的克隆
 }
private: //...
};

return *this返回的是当前对象的克隆或者本身(若返回类型为A, 则是拷贝, 若返回类型为A&, 则是本身 )。

return this返回当前对象的地址(指向当前对象的指针)

我们再来看看返回拷贝那个的地址~

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;
class Test
{
public:
 int x;
 Test get()
 {
  return *this; //返回当前对象的拷贝
 }
};
int main()
{
 Test a;
 a.x = 4;
 if(a.x == a.get().x)
 {
  cout << a.x << endl;
    cout << &a << endl;
    cout << &a.get() <<endl;
 }
 else
 {
  cout << "no" << endl;
    cout << &a << endl;
    cout << &a.get() <<endl;
 }
 
 return 0;
}

由运行结果得知会报下列错误!!!

cpp [Error] taking address of temporary [-fpermissive]

这是因为引用了临时对象的地址而引发的警报 临时对象不可靠……

所有要注意!

下面谈谈[C++]类成员返回语句 return *this 的理解

经常会在类似 copy-assignment 的成员函数看到返回语句 return *this ,这类函数通常返回类型是所属类的引用。

类成员函数的隐式指针 class *this const 经过 *this的解引用后成为此对象本身。此时若成员函数返回类型是 class ,那么返回的将是 this 指向的对象实体的拷贝;

若返回类型是 class& ,那么将返回一个绑定在 this 指向的对象实体上的引用。

总结

以上所述是小编给大家介绍的C/C++ 中return *this和return this的区别,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

原文链接:https://www.cnblogs.com/ZhuJD/archive/2019/10/21/11713937.html

延伸 · 阅读

精彩推荐