[英]c++ returning object from a function
下面的代码显示了一个代表复数的 class。 我的兴趣是了解operator+
function。 据我了解,应该在 function operator+
的框架上分配Complex res
。 将此 object 返回给调用者是否正确? 到此 function 返回时,帧将被弹出,但调用者将继续使用res
。 除非有比看起来更多的东西,比如实际的return res
可能实际上是将 object 从当前帧复制到调用者的帧。 另一种可能是operator+
function 内的代码可能内联在 main 的调用站点上? 根据我对语言的有限理解,在 class 中声明的函数默认内联在调用站点上。 任何帮助将不胜感激。
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
Complex operator+(Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.print();
}
阅读以下评论和答案后,添加以下部分以澄清解决方案
我用以下内容更新了上面的代码:
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
Complex operator+(Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
cout << "Address inside the function " << &res << "\n";
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
cout << "Address outside the function " << &c3 << "\n";
c3.print();
}
output 在堆栈的两个不同区域显示两个不同的地址,指示返回期间按值复制:
Address inside the function 0x7fffbc955610
Address outside the function 0x7fffbc955650
将此 object 返回给调用者是否正确?
C++ 支持按引用返回和按值返回。 由于您没有使用按引用返回,因此您没有将 object 的引用返回给调用者。 您正在使用按值返回,因此您将对象的值返回给调用者。 考虑:
int foo()
{
int i = 2;
return i;
}
这将返回值 2。它不返回 object i
。 return
后i
本身不再存在并不重要,因为它的值已经用于确定返回的值。
带值传输始终使用堆栈。 当你想返回一个值时,根据调用者代码,复制构造函数或赋值运算符可能会隐式调用并将返回值赋值给左边的object。 (左值)
Complex nwobj=cmpx1 + cmplx2; //copy constructor used to assign return object to lvalue
cmplx3=cmplx1+xmplx2;//operator= used to make a right assignment.
笔记:
根据使用的编译器及其设置,第一行中的复制构造可能会发生或可能会被省略。 可以在以下位置找到关于此的全面解释:
SO:什么是复制省略和返回值优化?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.