I am assuming that, You have already studied Part I,II and III of Operator Overloading Series. So i n this post, I am going to teach you How to perform Unary operator overloading using friend function. So, let's get started, //Overloading pre-increment operator using friend function #include<iostream> class A{ int length,breadth; public: A(int l, int b) { length=l; breadth=b; } friend void operator ++( A&); void display() { cout<<"Length: "<<length<<endl<<"Breadth: "<<breadth<<endl; } }; void operator ++( A& b); { ++b.length; ++b.breadth; } int main() { A a(7,14); ++a; //equivalent to operator ++(a); a.display(); return 0; } OUTPUT Length: 8 Breadth: 15 This is for pre-increment operator. In next post, I will teach you overloading binary operator using member function. So refer next post for that topic. If This post Helped you, Please leave a comment, and share with your Coder Friends. Thank You. Keep Lea...
I am assuming that, You have already studied previous parts of Operator Overloading Series. So i n this post, I am going to teach you How to Overload Insertion and Extraction operator. Here, I will overload '<<' and '>>' operator to input and output distance class data. So, let's get started, #include<iostream> using namespace std; class Distance{ int feet,inch; public: Distance(){ feet=0;inch=0; } Distance(int f,int i){ feet=f;inch=i; } friend ostream &operator <<(ostream &output , const Distance &d) { output<<"Feet: "<<d.feet<<" Inch: "<<d.inch<<endl; return output; } friend istream &operator >>(istream &input, Distance& d) { input>>d.feet>>d.inch; return input; } }; int main() { Distance d1(4,8), d2; cin>>d2; cout<<d1<<endl; cout<<d2; return 0; } In this ...
I am assuming that, You have already studied Part I and II of Operator Overloading Series. So i n this post, I am going to teach you How to do Unary operator Overloading . Before we get started towards our topic, I wanted to remind you, what Unary Operator Really is? An operator which acts upon only one operator is called unary operator. For example: Increment operator, Decrement operator and Negation operator (Minus) which acts as both unary as well as binary operator. Now, lets do coding to understand , how to perform unary operator overloading. Here, I will do Pre-Increment operator overloading. Have a look at this simple code and understand the basic. //Overloading pre-increment operator #include<iostream> class A{ int length,breadth; public: A(int l, int b) { length=l; breadth=b; } void operator ++() { ++length; ++breadth; } void display() { cout<<"Length: "<<length<<endl<<"Breadth: "<<breadth<<endl; } }; int main(...
Comments
Post a Comment