return *this和return this
来源:互联网 发布:可以美化图片的软件 编辑:程序博客网 时间:2024/05/21 09:08
看到书中的return *this比较疑惑,查询过后总结如下。
class temp{ ...;}
假如定义temp *get(){return this;}
,那么返回的this就是地址,即返回一个指向对象的指针
假如定义temp get(){return *this;}
那么返回的就是对象的克隆,是一个临时变量
假如定义temp &get(){return *this;}
那么返回的就是对象本身
例如:
#include<iostream>using namespace std;class A{ public: int x; A get() { return *this; }};int main(){ A a; A b; a.x = 4; if( a.x == a.get().x ) { cout << "asasas "; cout << a.x << endl; } else { cout << "no " << a.get().x << endl; } b = a.get(); cout << &b << " "<< &a << endl; cout << "b == " << b.x << endl; return 0;}
输出结果为
asasas 40x7ffdcfbb6650 0x7ffdcfbb6640b == 4
综上所述,return *this 返回的是对象的本身或克隆(具体看函数声明),return this 返回指针
这里我还犯过错误,在敲上述代码时,我试图看看返回的克隆对象的地址,即敲了&a.get();
这样的语句,结果是错误的,因为该函数返回对象的克隆,即一个临时变量,而临时变量的内存地址是不可取得的
阅读全文
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有什么区别?
- c++中return this和return *this的区别
- return *this和return this有什么区别?
- return this.vercode
- return this的用法
- return this.each(function(){})
- Backbone return this;
- Java return this
- JS return跳出方法和this属性
- getThis() { return this;}//getSuper() { return super.getThis();
- 今天看到的一个有趣面试题:return *this和return this有什么区别?
- 今天看到的一个有趣面试题:return *this和return this有什么区别?
- 今天看到的一个有趣面试题:return *this和return this有什么区别?
- linux在shell中获取时间date
- CCF考试——201609-3炉石传说
- PTA 6-1 循环单链表区间删除(15 分)
- android adb install Failure,提示base.apkcode is missing问题的解决
- html5图片上传【文件上传】
- return *this和return this
- 今日工作总结——调试Arduino——20171107
- Java并发之信号量
- vscode: Visual Studio Code 常用快捷键
- 论mysql中有“索引”和没有“索引”的查询速度
- boost编译
- c语言函数知识
- Another app is currently holding the yum lock; waiting for it to exit...
- 20171106