CC++中,return *this与return this有何本质区别?

2026-04-17 00:171阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计411个文字,预计阅读时间需要2分钟。

C/C++中,return *this与return this有何本质区别?

首先,我们需要了解这段代码的结构和功能。它是一个Java类的定义,名为`Test`,包含三个构造方法。以下是简化后的版本:

javaclass Test { Test() { return this; } // 返回当前对象的地址 Test() { return *this; } // 返回当前对象本身 Test() { return *this; } // 返回当前对象本身}

首先我们知道~

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

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

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

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

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

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

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

C/C++中,return *this与return this有何本质区别?

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

所有要注意!

本文共计411个文字,预计阅读时间需要2分钟。

C/C++中,return *this与return this有何本质区别?

首先,我们需要了解这段代码的结构和功能。它是一个Java类的定义,名为`Test`,包含三个构造方法。以下是简化后的版本:

javaclass Test { Test() { return this; } // 返回当前对象的地址 Test() { return *this; } // 返回当前对象本身 Test() { return *this; } // 返回当前对象本身}

首先我们知道~

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

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

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

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

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

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

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

C/C++中,return *this与return this有何本质区别?

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

所有要注意!