填空题 C++
题号 #2657221

为了满足运算符“+”的可交换性,必须将其重载为        。

进入在线模考

参考答案

暂无

答案解析

友元函数。
解析:以友元函数方式重载运算符可满足运算符“+”的可交换性,因为两个操作数都作为参数,例如,有以下程序:
#include<iostream.h>
class  Sample
{
       int n;
public:
       Sample(){}
       Sample(int i){n=i;}
       friend Sample operator+(Sample,Sample);
       void disp()  {cout<<“n=”<<n<<endl;  }
}
Sample operator+(sample s1,Sample s2)
{
    return sample(S1.n+s2.n);
}
void main()
{
    Sample S1(2),s2(5),s3;
    cout<<”S1:”;S1.disp();
    cout<<”s2:”;s2.disp();
    s3=S1+S2;
    cout<<”s3:”; s3.disp();
    S3=S2+S1;
    cout<<”s3:”;s3.disp();
}
程序执行结果如下:
从中看到,执行sl+s2和s2+sl的结果是相同的,从而满足运算符“+”的交换性。

你可能感兴趣的试题

找试题 · 找答案 · 找资料 在线模考