/*Copyright (c) 2011, 烟台大学计算机学院
* All rights reserved.
* 作 者: 石尧
* 完成日期:2014 年04 月 15日
* 版 本 号:v1.0
*
* 问题描述:利用友元函数实现运算符重载。
* 样例输入:略.
* 样例输出:略。
* 问题分析:略。
*/
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r; imag=i;}
Complex operator+(Complex &c2);
Complex operator-(Complex &c2);
Complex operator*(Complex &c2);
Complex operator/(Complex &c2);
friend void display(Complex &);
private:
double real;
double imag;
};
//下面定义成员函数
Complex Complex::operator+(Complex &c2)//定义复数相加函数
{
Complex c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}
Complex Complex::operator-(Complex &c2)
{
Complex c;
c.real=real-c2.real;
c.imag=imag-c2.imag;
return c;
}
Complex Complex::operator*(Complex &c2)
{
Complex c;
c.real=real*c2.real;
c.imag=imag*c2.imag;
return c;
}
Complex Complex::operator/(Complex &c2)
{
Complex c;
c.real=real/c2.real;
c.imag=imag/c2.imag;
return c;
}
void display(Complex &c)
{
cout<<"("<<c.real<<","<<c.imag<<"i)"<<endl;
}
//下面定义用于测试的main()函数
int main()
{
Complex c1(3,4),c2(5,-10),c3;
cout<<"c1=";
display(c1);
cout<<"c2=";
display(c2);
c3=c1+c2;
cout<<"c1+c2=";
display(c3);
c3=c1-c2;
cout<<"c1-c2=";
display(c3);
c3=c1*c2;
cout<<"c1*c2=";
display(c3);
c3=c1/c2;
cout<<"c1/c2=";
display(c3);
return 0;
}
心得体会:友元函数在调用时要将引用的数写在括弧内例如:display(c1),还有声明时不要忘记引用号&。
第八周项目1-2利用友元函数实现运算符重载
最新推荐文章于 2022-05-25 11:18:21 发布