c++ - 通过引用返回对象

标签 c++ class return-by-reference

#include<iostream>
using namespace std;
class my_class
{
    int m,n;
public:
    void show(void);
    my_class& test(my_class b)
    {
        static my_class c;
        c.m=m+b.m;
        c.n=n+b.n;
        return c;
    }
    my_class(int x,int y) //Parametrized constructor
    {
        m=x;n=y;
    }
    my_class(){} //Default consructor
};
void my_class::show(void)
{
    cout<<m<<" "<<n;
}
main()
{
    my_class a(2,3),b(3,4); //Object initialisation
    my_class d=a.test(b);
    d.show();
}

函数 test 返回对函数中定义的静态对象 c 的引用。我得到的输出为 5 7。我需要有关以下方面的帮助:

  • 我也可以通过返回 my_class 而不是 my_class& 来实现相同的输出。这里按值返回与按引用返回相比如何?返回的引用的数据成员是在赋值语句 my_class d=a.test(b) 中复制到对象 d?或者 d 只是返回引用的别名?
  • 如果我将赋值语句更改为 my_class& d=a.test(b), 即使那样我也得到相同的输出。这是否意味着这两种方式 写上面的语句对吗?

  • 能否请您解释一下这两种类型中到底发生了什么? 赋值语句?

最佳答案

How does return by value compare with return by reference here?Are data members of the returned reference copied in the assignment statement my_class d=a.test(b) to object d?

是的,d 是使用引用对象进行复制初始化的。 (虽然,这确实不是一项任务,也不是一项声明)。

...Or is d just an alias for the returned reference?

不,d 不是引用,也不是引用的别名。它是一个非引用变量。

If I changed the assignment statement to my_class& d=a.test(b), even then I get the same output?Does this mean that both ways of writing the above statement are right?

取决于权利的定义。这两个选项都不是病式的,但它们做的事情不同。什么是正确的取决于您打算做什么。

Can you please explain what exactly is happening in both the kinds of assignment statements?

  • 当您返回一个值时,会创建一个临时对象,该对象是从返回表达式复制初始化的。
  • 返回引用时,不会创建临时拷贝。
  • 当您从返回的临时文件进行复制初始化时,会创建另一个临时文件,并且隐式复制构造函数的引用参数会绑定(bind)到它。
  • 当您从返回的引用进行复制初始化时,隐式复制构造函数的引用参数绑定(bind)到返回的引用所引用的对象。
  • 当您将引用绑定(bind)到返回的引用时,它将绑定(bind)到引用的对象。

该标准允许省略一些提到的拷贝。

关于c++ - 通过引用返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37860638/

相关文章:

c++ - 未知错误可能是由命名冲突引起的?

c++ - QApplication::setWindowIcon 适用于 Windows XP,但不适用于 Windows 7

c++ - 区分添加剂类型?

python - 在 Django 中实例化 View 类时出错

c++如何将类声明为文件的本地类

c++ - Linux 中 C++ 应用程序的内存稳定性

node.js - 编译后从 typescript 命名空间导出类给出未定义(NestJS)

c++ - 返回指向局部变量的指针?? (警告 C4172)

C++ 返回值、引用、常量引用

c++ - 运算符重载 C++ 引用或值