zoukankan      html  css  js  c++  java
  • C++中this与*this的区别

    别跟我说, 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;
    }
    

    结果为: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返回的是当前对象本身(也就是其引用), 而非副本。
    https://blog.csdn.net/stpeace/article/details/22220777#

  • 相关阅读:
    2020-03-1811:29:37springboot与任务
    2020-03-17 20:18:50springboot整合rabbitmq
    2020.03.17 springboot缓存相关
    前端JS面试
    npm 常用指令
    ES8新特性
    ES7新特性
    ES6新特性
    SpringBoot
    SpringBoot
  • 原文地址:https://www.cnblogs.com/sggggr/p/15686227.html
Copyright © 2011-2022 走看看