专业网站的公司流量对网站的作用
以下是一个用运算符重载为友元重载的方法重做复数加减法的运算,请填空完成程序。
#include <iostream>
using namespace std;
class CComplex
{    
private:double real; double imag;
public:CComplex(double r=0.0,double i=0.0){ 
real(r), imag(i)}friend CComplex operator + (CComplex c1, CComplex c2);friend CComplex operator - (CComplex c1, CComplex c2);void display();
};
CComplexoperator + (CComplex c1, CComplex c2){return 
CComplex(c1.real + c2.real, c1.imag + c2.imag)
;}
CComplex operator - (CComplex c1, CComplex c2){return 
CComplex(c1.real - c2.real, c1.imag - c2.imag)
;}
void 
CComplex::display(){cout<<"("<<real<<","<<imag<<")"<<endl;}
int main()
{    CComplex c1(5,4),c2(2,10),c3,c4;cout<<"cl=";    c1.display();             cout<<"c2=";    c2.display();c3=c1-c2;        cout<<"c3=c1-c2=";    c3.display();c4=c1+c2;    cout<<"c4=c1+c2=";    c4.display();return 0;
}
 
数组重载的运算符[ ]
 分数 9
 作者 谢颂华
 单位 武汉理工大学
 已知一维数组类ARRAY的定义如下,ARRAY与普通一维数组区别是:其重载的运算符[ ]要对下标是否越界进行检查。
#include <iostream>
#include <string.h>
using namespace std;
class ARRAY{   int *v;       //指向存放数组数据的空间int s;        //数组大小  
public:   ARRAY(int a[], int n){if(n<=0) {v=NULL;s=0;return;}s=n;v= new int[n];for(int i=0; i<n; i++) v[i]=a[i];}~ ARRAY(){delete []v;}int size(){ return s;} int& operator[](int n); 
};
int& ARRAY::
operator[](int n)  //[ ]的运算符成员函数定义
{if(n<0 || 
n >= s
) {cerr<<"下标越界"; }return 
v[n]
;
}int main()
{int x[]={2,4,6,8};ARRAY A(x,4);for(int i=0; i<4; i++)cout<<A[i]<<" ";return 0;
}
 
Point类运算符+重载为友元
 分数 12
 作者 谢颂华
 单位 武汉理工大学
#include <iostream>
using namespace std;
class Point
{private:int x, y;public:Point(){x=y=0;}Point(int x0,int y0) {x=x0;y=y0;}int GetX() { return x; }int GetY() { return y; }void Print(){cout<<"Point("<<x<<","<<y<<")"<<endl;}friend Point operator+(Point& pt, int dd)
;  //友元函数声明friend Point operator+(Point& pt1, Point& pt2)
;  //友元函数声明
};Point operator+(Point& pt,int dd) //加号操作符重载函数,实现Point类对象与整数加法
{Point temp=pt;temp.x+=dd;temp.y+=dd;return temp
;
}Point operator+(Point& pt1,Point& pt2) //加号操作符重载函数,实现两个Point类对象的加法
{Point temp=pt1;temp.x+=pt2.x;temp.y += pt2.y
;return temp;
}
int main() {Point A(1,4),B(2,3),C;int x=8;C=A+8;C.Print();C=A+B;C.Print();return 0;
}  
