第八周——重载运算符——项目一(2)利用友元函数实现+-*/重载

问题及代码:
/*
*Copyright (c) 2014,烟台大学计算机学院
*All rights reserved.
*文件名称:lily.cpp
*作者:李莉
*完成日期:2015年4月2日
版本号:v1.0
*
*问题描述:项目1-实现复数类中的运算符重载】
(1)请用类的成员函数,定义复数类重载运算符+、-、*、/,使之能用于复数的加减乘除
*程序输入:无输入
*程序输出:运算后的结果
*/
#include
using namespace std;
class Complex
{
public:
    Complex(){real=0;imag=0;}
    Complex(double r,double i){real=r; imag=i;}
    friend Complex operator+(const Complex &c1, Complex &c2);
    friend Complex operator-(const Complex &c1, Complex &c2);
    friend Complex operator*(const Complex &c1, Complex &c2);
    friend Complex operator/(const Complex &c1, Complex &c2);
    void display();
private:
    double real;
    double imag;
};
Complex operator+(const Complex &c1, Complex &c2)
{
    Complex c;
    c.real=c1.real+c2.real;
    c.imag=c1.imag+c2.imag;
    return c;
}
Complex operator-(const Complex &c1, Complex &c2)
{
    Complex c;
    c.real=c1.real-c2.real;
    c.imag=c1.imag-c2.imag;
    return c;
}
Complex operator*(const Complex &c1, Complex &c2)
{
    Complex c;
    c.real=c1.real*c2.real-c1.imag*c2.imag;
    c.imag=c1.imag*c2.real+c1.real*c2.imag;
    return c;
}
Complex operator/(const Complex &c1, Complex &c2)
{
    Complex c;
    c.real=(c1.real*c2.real+c1.imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
    c.imag=(c1.imag*c2.real-c1.real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
    return c;

}
void Complex::display()
{
    cout<<"("<第八周——重载运算符——项目一(2)利用友元函数实现+-*/重载_第1张图片

你可能感兴趣的:(学习,对象,重载运算符)