gpt4 book ai didi

c++ - 为什么可以在 C++ 的函数内返回对象引用?

转载 作者:太空狗 更新时间:2023-10-29 19:38:51 24 4
gpt4 key购买 nike

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

// 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;
}

最佳答案

在您的示例中,您不返回对象引用,您只需按值返回对象。

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

关于c++ - 为什么可以在 C++ 的函数内返回对象引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6556413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com