Develop a C++ program to add two complex number by overloading + operator using Member function.
class ComplexNumber
{
public:
ComplexNumber(){}
ComplexNumber( double RealPart, double ImgPart ) : realPart( RealPart ), imgPart( ImgPart ){}
//Member function to add complex number
ComplexNumber operator+ (const ComplexNumber& otherNumber) const
{
return ComplexNumber(this->realPart + otherNumber.realPart, this->imgPart + otherNumber.imgPart );
}
//Member function to subtract complex number
ComplexNumber operator- (const ComplexNumber& otherNumber) const
{
return ComplexNumber(this->realPart - otherNumber.realPart, this->imgPart - otherNumber.imgPart);
}
void operator= (const ComplexNumber& otherNumber)
{
realPart = otherNumber.realPart;
imgPart = otherNumber.imgPart;
}
private:
double realPart = 0;
double imgPart = 0;
};
int main()
{
ComplexNumber A(1, 2);//complex number A = 1 + 2i
ComplexNumber B(3, 4);//complex number B = 3 + 4i
ComplexNumber R;//complex number R = 0 + 0i
R = A + B;//now R = 4 + 6i
return 0;
}
Comments
Leave a comment