C ++引用和非引用返回类对象 - 为什么输出相同? [英] C++ reference and non reference return of class object- why output same?

查看:96
本文介绍了C ++引用和非引用返回类对象 - 为什么输出相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

class Test  
{  
    public:  
    int data;

    Test() { data = 9; }

    Test myfunction ();
    void print() { cout << data<<endl; }
};  

Test m;
Test Test::myfunction ()
{
    return m;
};    


int main()
{   
    Test b;
    Test a;
    b=a.myfunction();
    b.print();

    return 0;
}

即使我只是替换函数以下,输出保持不变(我不更改任何东西在主要部分)。为什么会这样呢?

even if i only replace the function with the following, the output remains the same ( i do not change anything inside the main section). why is that so?

class Test  
{  
    public:  
    int data;

    Test() { data = 9; }

    Test& myfunction ();
    void print() { cout << data<<endl; }
};  

Test m;

// function replaced and now it has reference return
Test& Test::myfunction ()
{
    return m; 
};   


int main()
{   
    Test b;
    Test a;
    b=a.myfunction();
    b.print();

    return 0;
}

两种情况之间的区别是什么? >
i对于引用没有多大作用,请详细说明。

what is the difference between both the cases.? i have not worked much with references so please explain in detail.

两种编译都很好,输出结果如下:
9

Both compiles fine with output in each case as: 9

推荐答案

在第一个代码段中,返回全局实例 m 的副本。在你的情况下,编译器生成一个< em>平凡的复制构造函数,将复制你的成员 data 。此外,您还可以生成一个生成的小型复制赋值操作符,将结果复制到 b ,同时复制您的成员 data 自动。

In the first snippet you return a copy of the global instance m. In your case the compiler generates a trivial copy constructor, that will copy your member data. Also, you get a trivial trivial copy assignment operator generated which copies the result to b, also copying your member data automatically.

第二个版本返回对全局实例 m 的引用。从这一点上它的工作原理与第一种情况相同:result被分配给 b 。它只是 Test 的一个复制操作。

The second version returns a reference to the global instance m. From this point it works the same as the first case: result is being assigned to b. It's just one copy operation of Test less.

这篇关于C ++引用和非引用返回类对象 - 为什么输出相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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