return *this和return this有什么区别?
来源:互联网 发布:mysql安装的默认密码 编辑:程序博客网 时间:2024/06/07 03:57
return *this返回当前对象, return this返回当前对象的地址(指向当前对象的指针)。 结果为:yes 结果为:
正确答案为: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)有什么区别?
- Finance系列(7)之International Trade
- 模式识别分类
- iris-session梳理
- 5 分钟搞定 Java Comparable 接口
- 34. Search for a Range
- return *this和return this有什么区别?
- Centos搭建持续集成(二)----安装Tomcat
- java线程池(1)初识线程池
- Spring学习(2)--在xml中使用autowire自动装配Bean属性
- 提高代码阅读能力的7种方法
- 这70个Java必背英语单词不会,就别说你是Java程序员!
- 使用canvas与Paint在View中居中绘制文字
- 线程安全与共享资源
- Java 并发开发:Lock 框架详解