下面的代码展示了一个表示复数的类。我对理解
输出结果显示栈的两个不同区域上有两个不同的地址,表明返回时进行了值复制。
operator+
函数很感兴趣。据我所知,Complex res
应该在 operator+
函数的框架上分配。将该对象返回给调用者是否正确?当这个函数返回时,该框架已经弹出,但是 res
对象仍将被调用者使用。除非有更多的细节需要注意,例如实际的 return res
可能会将对象从当前框架复制到调用者的框架中。另一个可能性是,在主调用点上内联 operator+
函数中的代码?根据我有限的语言理解,声明在类内部的函数默认情况下会在调用点上进行内联处理。任何帮助都将不胜感激。#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();
}
输出结果显示栈的两个不同区域上有两个不同的地址,表明返回时进行了值复制。
Address inside the function 0x7fffbc955610
Address outside the function 0x7fffbc955650
operator+
中,我添加了以下行cout << "函数内部地址 " << &res << "\n";
在main
中,我添加了以下行cout << "函数外部地址 " << &c3 << "\n";
。我得到了两个不同的地址,表明了您提到的按值复制。 - sshekhar1980