return *this和return this有什么区别?
来源:互联网 发布:全球经济数据时时播报 编辑:程序博客网 时间:2024/05/28 05:19
别跟我说, 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;
- }
再看:
- #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返回的是当前对象本身(也就是其引用), 而非副本。
0 0
- 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和return this
- return *this和return this
- c++中return this和return *this的区别
- return null; 和 return;有什么区别
- return this与return *this
- C#中的yield return 和return有什么区别
- js中return和return false有什么区别
- javascript中return、return false、return true有什么区别?
- this、 $("this")、$(this)有什么区别
- e.target和this有什么区别?
- jQuery里面用this和用$(this)有什么区别?
- 总结iOS 多线程学习过程四
- Spark修炼之道(基础篇)——Linux大数据开发基础:第十节:Shell编程入门(二)
- VC多线程编程之一——问题提出
- poj 3614
- 遍历容器 Java风格和STL风格 foreach
- return *this和return this有什么区别?
- cenos7.1 安装openstack kilo 心得之三添加网络时间协议
- phpstorm常用快捷键
- 杭电1072 猜数字
- 工业4.0时代已经到来,你准备好了吗?
- LeetCode---Simplify Path
- Modules 'libxmlSimu' not found 在使用XMPP时导入KissXML时出现的问题
- 创建型设计模式:简单工厂模式--分析优缺点
- struct和typedef struct彻底明白了