Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //operator+
- // how to do with no operator+
- #include <iostream>
- using namespace std;
- class complex
- {
- private:
- int real;
- int img;
- public:
- complex(int a=0 , int b=0 ){ // non parameterized or default constructor
- real = a;
- img = b;
- }
- complex add(complex x){
- complex temp; // creating new object, if no value passed defaulf it will be zero
- temp.real = real + x.real;
- temp.img = img + x.img;
- return temp;
- }
- void show(){
- cout<<real<<" + i"<<img<<endl;
- }
- };
- int main()
- {
- complex c1(8,5) , c2(1,7);
- complex c3 = c1.add(c2); // complex c3 = c2.add(c1);
- c1.show();
- c2.show();
- c3.show();
- return 0;
- }
- // if you want to do same thing as above code has done using opertor+ see below code
- #include <iostream>
- using namespace std;
- class complex
- {
- private:
- int real;
- int img;
- public:
- complex(int a=0 , int b=0 ){ // non parameterized or default constructor
- real = a;
- img = b;
- }
- complex operator+(complex x){
- complex temp; // creating new object, if no value passed defaulf it will be zero
- temp.real = real + x.real;
- temp.img = img + x.img;
- return temp;
- }
- void show(){
- cout<<real<<" + i"<<img<<endl;
- }
- };
- int main()
- {
- complex c1(8,5) , c2(1,7);
- complex c3 = c1 + c2;
- c1.show();
- c2.show();
- c3.show();
- return 0;
- }
- // same operator+ but with friend function
- #include <iostream>
- using namespace std;
- class complex
- {
- private:
- int real;
- int img;
- public:
- complex(int a=0 , int b=0 ){ // non parameterized or default constructor
- real = a;
- img = b;
- }
- friend complex operator+(complex x , complex y);
- void show(){
- cout<<real<<" + i"<<img<<endl;
- }
- };
- complex operator+(complex x , complex y){
- complex temp; // creating new object, if no value passed defaulf it will be zero
- temp.real = x.real + y.real;
- temp.img = x.img + y.img;
- return temp;
- }
- int main()
- {
- complex c1(8,5) , c2(1,7);
- complex c3 = c1 + c2; // complex c3 = c2.add(c1);
- c1.show();
- c2.show();
- c3.show();
- return 0;
- }
- /*
- Output
- 8 + i5
- 1 + i7
- 9 + i12
- */
Add Comment
Please, Sign In to add comment