Last active
January 13, 2019 18:04
-
-
Save theArjun/6e196d6eb6db1746fe48a8882404127a to your computer and use it in GitHub Desktop.
Operator Overloading for '+' , '- ' and '='.
This file contains hidden or 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
| // Q. Write a program with class Distance to realize following main method. | |
| // [Internal 2018 Spring - GCES] | |
| #include<iostream> | |
| using namespace std; | |
| class Distance{ | |
| private: | |
| int cm; | |
| public: | |
| Distance():cm(0){} | |
| Distance(int c):cm(c){} | |
| Distance operator + (int); | |
| void operator = (Distance); | |
| void operator = (int); | |
| int operator - (int); | |
| void display(); | |
| }; | |
| Distance Distance :: operator +(int another){ | |
| Distance temporary; | |
| temporary.cm = this->cm + another; | |
| return temporary; | |
| } | |
| void Distance :: operator =(Distance another){ | |
| this->cm = another.cm; | |
| } | |
| void Distance :: operator = (int another){ | |
| this->cm = another; | |
| } | |
| int Distance :: operator - (int another){ | |
| int temporary; | |
| temporary = this->cm - another; | |
| return temporary; | |
| } | |
| void Distance :: display(){ | |
| cout << cm; | |
| } | |
| int main(){ | |
| Distance d1 = 202; // 200 is cm | |
| Distance d2 = d1 + 333; // 333 is cm | |
| cout << "sum is " << endl; | |
| d2.display(); | |
| int diff = d1 -22; // diff is in cm | |
| cout << "difference is " << endl; | |
| cout << diff; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment