《转》return *this和 return this有什么区别?
2018-06-01 20:33
316 查看
别跟我说 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 返回的是当前对象本身(也就是其引用),而非副本。
相关文章推荐
- return *this和return this有什么区别?
- 今天看到的一个有趣面试题:return *this和return this有什么区别?
- return *this和return this有什么区别?
- return *this和return this有什么区别?
- return *this和return this有什么区别?
- 今天看到的一个有趣面试题:return *this和return this有什么区别?
- 今天看到的一个有趣面试题:return *this和return this有什么区别?
- 【JS】JS中return;、return true、return false之间有什么区别?
- init()方法里的这三个,有什么区别?this.getServletConfig().getInitParameter("username")+"----"+this.getServletConte
- 函数调用方式--__thiscall调用方式和__cdecl,__stdcall有什么区别
- 在while循环中,break,continue,return有什么区别??
- onclick="f1()"和onclick="return f1()"的区别是什么?
- jquery里面的$(this)和this都什么时候用,有什么区别
- exit(0),return 0有什么区别
- 支付宝支付接口中 notify_url 与 return_url 的区别是什么
- 函数调用方式--__thiscall调用方式和__cdecl,__stdcall有什么区别
- jquery里面的$(this)和this都什么时候用,有什么区别
- javascript中return、return false、return true有什么区别?
- 函数调用方式--__thiscall调用方式和__cdecl,__stdcall有什么区别