Created
March 24, 2013 21:27
-
-
Save lahwaacz/5233608 to your computer and use it in GitHub Desktop.
operator+ overload example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyComplex | |
{ | |
private: | |
double real, imag; | |
public: | |
MyComplex(){ | |
real = 0; | |
imag = 0; | |
} | |
MyComplex(double r, double i) { | |
real = r; | |
imag = i; | |
} | |
double getReal() const { | |
return real; | |
} | |
double getImag() const { | |
return imag; | |
} | |
MyComplex & operator=(const MyComplex &); | |
friend const | |
MyComplex operator+(const MyComplex&, const MyComplex&); | |
}; | |
MyComplex & MyComplex::operator=(const MyComplex& c) { | |
real = c.real; | |
imag = c.imag; | |
return *this; | |
} | |
/* This is not a member function of MyComplex class */ | |
const MyComplex operator+(const MyComplex& c1, const MyComplex& c2) { | |
MyComplex temp; | |
temp.real = c1.real + c2.real; | |
temp.imag = c1.imag + c2.imag; | |
return temp; | |
} | |
#include <iostream> | |
int main() | |
{ | |
using namespace std; | |
MyComplex c1(5,10); | |
MyComplex c2(50,100); | |
cout << "c1= " << c1.getReal() << "+" << c1.getImag() << "i" << endl; | |
cout << "c2= " << c2.getReal() << "+" << c2.getImag() << "i" << endl; | |
c2 = c1; | |
cout << "assign c1 to c2:" << endl; | |
cout << "c2= " << c2.getReal() << "+" << c2.getImag() << "i" << endl; | |
cout << endl; | |
MyComplex c3(10,100); | |
MyComplex c4(20,200); | |
cout << "c3= " << c3.getReal() << "+" << c3.getImag() << "i" << endl; | |
cout << "c4= " << c4.getReal() << "+" << c4.getImag() << "i" << endl; | |
MyComplex c5 = c3 + c4; | |
cout << "adding c3 and c4" << endl; | |
cout << "c3= " << c3.getReal() << "+" << c3.getImag() << "i" << endl; | |
cout << "c4= " << c4.getReal() << "+" << c4.getImag() << "i" << endl; | |
cout << "c5= " << c5.getReal() << "+" << c5.getImag() << "i" << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment