今天看到的一个有趣面试题:return *this和return this有什么区别?
2014-03-26 22:53
246 查看
别跟我说, return *this返回当前对象, return this返回当前对象的地址(指向当前对象的指针)。
正确答案为:return *this返回的是当前对象的克隆或者本身(若返回类型为A, 则是克隆, 若返回类型为A&, 则是本身 )。return this返回当前对象的地址(指向当前对象的指针), 下面我们来看看程序吧:
再看:
4
no
最后, 如果返回类型是A&, 那么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有什么区别?
- 今天看到一个sql的面试题,我想应该记录一下
- 【安卓面试题】在一个Activity启动另一个Activity和在Service中启动一个Activity有什么区别
- 《转》return *this和 return this有什么区别?
- 那天在CSDN上看到一个网友在华为遇到的面试题是一道乘法题看似简其实并不是因为它们都超出了数据类型的范围,今天做了下加法希望对大家有所启示
- 今天看到一个面试题,要求查询一个有姓名,分数,科目的表 变为根据科目分类
- onclick="f1()"和onclick="return f1()"的区别是什么?
- 今天路上看到一个老人摔倒……
- 网上看到一个的网易面试题
- 前端面试题-----js和jquery的区别是什么?
- htm和html之间一个字母的区别,你知道意味着什么吗?
- 函数调用方式--__thiscall调用方式和__cdecl,__stdcall有什么区别
- 面试题:下面的代码有什么不妥之处?(字符串、一个字符串常量比较内容)
- 使用临时表与声明一个表数据类型的变量有什么区别
- JAVA在定义一个方法的时候,不用public和用public有什么区别?