#include "stdafx.h"
#include
using namespace std;
//the implementation of the complexType class
class complexType
{
//overload the stream insertion and extraction operator
friend ostream& operator<<(ostream&,const complexType&);
friend istream& operator>>(istream&,complexType&);
public:
void setComplex(const double& real,const double& imag);
//Function to set the complex numbers according to
//the parameters.
complexType(double real=0,double imag=0);
//overload the operator +
//never return & to avoid the operation a+b=c
complexType operator+(const complexType& otherComplex) const;
//overload the operator *
//never return & to avoid the operation a*b=c
complexType operator *(const complexType& otherComplex) const;
//overload the operator ==
bool operator ==(const complexType& otherComplex) const;
private:
double realPart; //variable to store the real part
double imaginaryPart; //variable to store the imaginary part
};
//output (a,b)
//return & to insure that cout<ostream& operator<<(ostream& osObject,const complexType& complex)
{
osObject<<"(";
osObject< osObject<<",";
osObject< osObject<<")";
return osObject;
}
//when input (a,b),discard (,)
//return & to insure that cin>>x>>b is correct
istream& operator>>(istream& isObject,complexType& complex)
{
char ch;
isObject>>ch;
isObject>>complex.realPart ;
isObject>>ch;
isObject>>complex.imaginaryPart ;
isObject>>ch;
return isObject;
}
//the implementation of other member functions
bool complexType::operator ==(const complexType& otherComplex) const
{
return (realPart==otherComplex.realPart &&
imaginaryPart==otherComplex.imaginaryPart );
}
void complexType::setComplex(const double& real,const double& imag)
{
realPart=real;
imaginaryPart=imag;
}
//constructor
complexType::complexType (double real,double imag)
{
setComplex(real,imag);
}
//overload the operator +
complexType complexType::operator +(const complexType& otherComplex) const
{
complexType temp;
temp.realPart =realPart+otherComplex.realPart;
temp.imaginaryPart =imaginaryPart+otherComplex.imaginaryPart ;
return temp;
}
//overload the operator *
complexType complexType::operator *(const complexType& otherComplex) const
{
complexType temp;
temp.realPart =(realPart*otherComplex.realPart)-
(imaginaryPart*otherComplex.imaginaryPart);
temp.imaginaryPart =(realPart*otherComplex.imaginaryPart)
+(imaginaryPart*otherComplex.realPart );
return temp;
}
//Program that uses the class complexType
int main()
{
complexType num1(23,34);
complexType num2;
complexType num3;
cout<<"Num1="< cout<<"Num2="<
cout<<"Enter the complex number in the form (a,b)"< cin>>num2;
cout<
cout<<"The new value of Num2="<
num3=num1+num2;
cout<<"Num3="<
cout< cout< return 0;
}
阅读(543) | 评论(0) | 转发(0) |