Problem:
(1) Use the member function of the class to define the plural class overloaded operator + 、-、 *,/, so that it can be used for the subtraction of a complex number
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 ();p rivate: double real; Double imag;};/ /below defines the member function//The following defines the main () function used for testing int main () { Complex C1 (3,4), C2 (5,-10), C3; cout<< "c1="; C1.display (); cout<< "c2="; C2.display (); C3=C1+C2; cout<< "c1+c2="; C3.display (); C3=C1-C2; cout<< "c1-c2="; C3.display (); C3=C1*C2; cout<< "c1*c2="; C3.display (); C3=C1/C2; cout<< "c1/c2="; C3.display (); return 0;}
Code
/* Copyright (c) 2015, Yantai University School of Computer * All rights reserved. * File name: Test.cpp * Author: Lenkidong * Completion Date: April 23, 2015 * version number: v1.0*/#include <iostream>using namespace Std;class comple X{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 ();p rivate:double Real; Double imag;};/ //The following defines member functions//additions: (A+BI) + (C+di) = (a+c) + (b+d) I.complex complex::operator+ (const Complex &C2) {Complex C; C.real=real+c2.real; C.imag=imag+c2.imag; return c;} Subtraction: (A+BI)-(C+di) = (a-c) + (b-d) I.complex complex::operator-(const Complex &C2) {Complex C; C.real=real-c2.real; C.imag=imag-c2.imag; return c;} Multiply: (A+BI) * (C+di) = (AC-BD) + (Bc+ad) I.complex complex::operator* (const Complex &C2) {Complex C; C.real=real*c2.real-imag*c2.imag; C.imag=imag*c2.real+real*c2.imag; return c;} Subtract: (A+BI)/(C+di) = (AC+BD)/(CC+DD) + (Bc-ad) i/(CC+DD). Complex complex::operator/(const Complex &C2) {Complex C; C.real= (Real*c2.real+imag*c2.imag)/(C2.imag*c2.imag+c2.real*c2.real); c.imag= (Imag*c2.real-real*c2.imag)/(C2.imag*c2.imag+c2.real*c2.real); return c;} void Complex::d isplay () {cout<< "(" <<real<< "," <<imag<< ")" <<ENDL;} The following defines the main () function for testing int main () {Complex C1 (3,4), C2 (5,-10), C3; cout<< "c1="; C1.display (); cout<< "c2="; C2.display (); C3=C1+C2; cout<< "c1+c2="; C3.display (); C3=C1-C2; cout<< "c1-c2="; C3.display (); C3=C1*C2; cout<< "c1*c2="; C3.display (); C3=C1/C2; cout<< "c1/c2="; C3.display (); return 0;}
Operation Result:
Practiced hand
Learning experience:
Study hard and cheer up
Week eighth item one-operator overloading in the plural class (1)