用类的成员函数定义复数类重载运算符





/*
*Copyright (c) 2016,烟台大学计算机学院
*All rights reserved.
*文件名称:text.cpp
*作者:陈传祯
*完成日期:2016年5月31日
*版本号: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+(const Complex&c2);
        Complex operator-(const Complex&c2);
         Complex operator*(const Complex&c2);
          Complex operator/(const Complex&c2);
          void display();
   private:
    double real;
    double imag;
};
Complex Complex::operator+(const Complex&s2)
{
    return Complex(real+s2.real,imag+s2.imag);
}
Complex Complex::operator-(const Complex&s2)
{
   return Complex(real-s2.real,imag-s2.imag);
}
Complex Complex::operator*(const Complex&s2)
{
   return Complex(real*s2.real,imag*s2.imag);
}
Complex Complex::operator/(const Complex&s2)
{
    return Complex(real/s2.real,imag/s2.imag);
}
void Complex :: display()
{
    cout<<"("<<real<<","<<imag<<")"<<endl;
}
int main()
{
    Complex c1(5,10),c2(6,-6),c3;
    cout<<"c1="<<endl;
    c1.display();
        cout<<"c2="<<endl;
    c2.display();
        c3=c1+c2;
        cout<<"c1+c2="<<endl;
    c3.display();
            c3=c1-c2;
        cout<<"c1-c2="<<endl;
    c3.display();
            c3=c1*c2;
        cout<<"c1*c2="<<endl;
    c3.display();
            c3=c1/c2;
        cout<<"c1/c2="<<endl;
    c3.display();
    return 0;
}
阅读更多
上一篇运算符重载加法(单目)
下一篇c++
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭