为什么在c ++中的函数内部返回对象引用是可行的? [英] Why is it OK to return an object reference inside a function in c++?

查看:136
本文介绍了为什么在c ++中的函数内部返回对象引用是可行的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是网站上的示例: http://www.cplusplus.com/doc/ tutorial / classes2 /
我知道这是一个工作示例。但是,我不明白为什么对象temp可以从操作符+重载函数返回。我除了代码之外还做了一些评论。

Here is an example from website: http://www.cplusplus.com/doc/tutorial/classes2/ I know it is a working example. However, I don't understand why object temp can be returned from the operator+ overloading function. I have made some comments besides the codes.

// vectors: overloading operators example
#include <iostream>
using namespace std;

class CVector {
  public:
    int x,y;
    CVector () {};
    CVector (int,int);
    CVector operator + (CVector);
};

CVector::CVector (int a, int b) {
  x = a;
  y = b;
}

CVector CVector::operator+ (CVector param) {
  CVector temp;
  temp.x = x + param.x;
  temp.y = y + param.y;
  return (temp);   ***// Isn't object temp be destroyed after this function exits ?***
}

int main () {
  CVector a (3,1);
  CVector b (1,2);
  CVector c;
  c = a + b; ***// If object temp is destroyed, why does this assignment still work?***
  cout << c.x << "," << c.y;
  return 0;
}


推荐答案

t返回一个对象引用,你只需通过值返回对象。

In your example you don't return an object reference, you simply return the object by value.

对象temp实际上在函数退出后被销毁,但是当时它的值被复制到堆栈。

Object temp is in fact destroyed after the function exits but by that time its value is copied on the stack.

这篇关于为什么在c ++中的函数内部返回对象引用是可行的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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