函数在c ++中返回这个指针 [英] function returning this pointer in c++

查看:105
本文介绍了函数在c ++中返回这个指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个代码:

#include <iostream>
using namespace std;
class demo
{
  int a;
public:
  demo():a(9){}
  demo& fun()//return type isdemo&
  {
    return *this;
  }
};

int main()
{
  demo obj;
  obj.fun();
  return 0;
}

第二个代码:

#include <iostream>
using namespace std;
class demo
{
  int a;
public:
  demo():a(9){}
  demo fun()//return type is demo
  {
    return *this;
  }
};

int main()
{
  demo obj;
  obj.fun();
  return 0;
}

这两个代码之间的区别是什么?

what is the difference between these two codes as both are working in gcc?i am new here so forgive me if my way of asking is wrong.

推荐答案

演示& fun()返回对当前对象的引用。 demo fun()返回由复制当前对象所产生的对象。

demo & fun() returns a reference to the current object. demo fun() returns a new object, made by copying the current object.

这篇关于函数在c ++中返回这个指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆