return *this和return this有什么区别?
2017-12-10 11:36
399 查看
return *this返回当前对象, return this返回当前对象的地址(指向当前对象的指针)。
正确答案为:return *this返回的是当前对象的克隆或者本身(若返回类型为A, 则是克隆, 若返回类型为A&, 则是本身 )。return this返回当前对象的地址(指向当前对象的指针), 下面我们来看看程序吧:
[cpp]
view plain
copy
#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
再看:
[cpp]
view plain
copy
#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返回的是当前对象的克隆或者本身(若返回类型为A, 则是克隆, 若返回类型为A&, 则是本身 )。return this返回当前对象的地址(指向当前对象的指针), 下面我们来看看程序吧:
[cpp]
view plain
copy
#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
再看:
[cpp]
view plain
copy
#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有什么区别?
- Android中this.*与*.this还有*.class的区别是什么?
- 在while循环中,break,continue,return有什么区别??
- 函数调用方式--__thiscall调用方式和__cdecl,__stdcall有什么区别
- 在while循环中,break,continue,return有什么区别?
- return null; 和 return;有什么区别
- c++中return this和return *this的区别
- Android中this.*与*.this还有*.class的区别是什么?
- Android中this.*与*.this还有*.class的区别是什么?
- html、text、val、attr、prop区别。this.value和$(this).val()区别以及return用法
- ES6---箭头函数与function定义函数有什么区别?在箭头函数中,this指向,构造函数,变量提升是如何表现的?
- 函数调用方式--__thiscall调用方式和__cdecl,__stdcall有什么区别
- return与exit的区别是什么?
- init()方法里的这三个,有什么区别?this.getServletConfig().getInitParameter("username")+"----"+this.getServletConte