任何机构都可以在运算符重载中解释这行代码

Can any body please explain this line of code in operator overloading for the plus

本文关键字:解释 代码 重载 机构 都可以 运算符 任何      更新时间:2023-10-16

下面的代码用于使用运算符重载添加两个复数,但我不明白加号运算符的参数和主体。谁能解释一下?

complex operator+(complex a2) // why this argument is used please explain 
{  
complex a;  //what is the need of this
a.r=r+a2.r;  //and how it is being done 
a.i=i+a2.i;  //this one too
return a;  
}

我知道复杂是一个类,a 是它的对象,但我幻想为什么我们使用 a2。

问题中的运算符处理将两个complex对象相加以形成新的临时值的情况:

a1 + a2

当编译器看到该表达式时,它会创建第三个(临时)值,即它们的总和。

它通过将+视为表达式左侧的成员函数来实现此目的。所以上面的代码等效于这个:

a1.operator+(a2); // member function call

所以函数的主体是对象a1的成员函数的主体

complex operator+(complex a2) // member function of a1 receiving a2 as a parameter 
{  
complex a;       // this is the new value that will be created from a1 + a2
a.r = r + a2.r;  // r is a1.r because this object is a1 
a.i = i + a2.i;  // same with i
return a;        // the (temporary) result is returned
}

当临时结果分配给命名变量时,才会使用临时结果,如下所示:

a = a1 + a2;
complex operator+(complex a2) // why this argument is used please explain 
{  
complex a;  //what is the need of this
a.r=r+a2.r;  //and how it is being done 
a.i=i+a2.i;  //this one too
return a;   
}

你的问题是"我不明白加号运算符的论点和主体"和"我知道复杂是一个类,a 是它的对象,但我幻想为什么我们使用 a2。

考虑一下,如果在定义重载函数时不complex a2对象作为参数传递complex operator+()它将产生错误消息,因为它需要一个参数。

当您在 main 函数中创建complex类的对象时complex a2帮助您传递任何其他对象的值以进行求和运算。

这是一个演示。

#include<iostream>
using namespace std;
class N{
private:
int x,y;
public:
N(int a=0,int b=0)
{
x=a;
y=b;
}
void print(){
cout<<x<<" : "<<y<<endl;
}
N operator+(N a)
{
x=a.x;
}
};
int main(){
N b;
N a(2,3);
a.print();
b.print();
b.operator+(a);
b.print();
return 0;
}  

希望你已经了解complex a2论点。如果没有,请在下面发表评论。

运算符重载通常意味着您可以执行比该运算符通常执行的操作更多的事情。 在这里,您使用"+"运算符重载添加两个复数。所以你正在做这样的事情。

结果 = A1+ A2,其中 a1 和 a2 是两个复数 分别有实部和虚部。 将 +operator 视为函数名称,那么如何将参数传递给函数。a2 是您要与 a1 相加的另一个数字,因此 a2 作为参数进入,该参数也是复杂类型,并且该函数将复杂对象返回为"a",其中包括实部和虚部。 我希望我回答你所寻求的。

complex operator+(complex a2) // why this argument is used please explain 
{  
complex a;  //what is the need of this
a.r=r+a2.r;  //and how it is being done 
a.i=i+a2.i;  //this one too
return a;  
}

答 1.complex operator+(complex a2)
complex指定返回类型将是type class complexcomplex a2指定运算符将用于class complex的对象。

答 2.complex a;这是对类复合体的对象和数据成员执行临时操作所必需的。把它想象成一个temp变量,你引入一个变量,在一个函数中将 2 个数字相加,稍后返回它。

答 3.a.r=r+a2.r;好的,现在你已经欺骗了类复合体的一个临时对象,你说存储a2r调用这个重载函数r的对象的总和,并将其存储到临时对象的r中。

答 4.a.i=i+a2.i;同上。

然后,您将临时对象returna计算的总和为ri。请注意,atypeclass complex的,因此返回类型在第 1 行中指定为complex

如果您还看到main()函数中使用的运算符,您将更好地理解它。

complex x,y,z;
x=y+z;

这里x将获取临时对象a的值。调用变量ya2将收到z。就像在这里呼唤+一样x = y.overloaded_plus(z) // only for explanation