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 ...
In this post, I am going to teach you Basic Concept of OPERATOR OVERLOADING . So, let's get started, Firstly, What is overloading? Here is the Answer : Overloading refers to the ability to use a single identifier to define multiple methods of a class that differ in their input and output parameters. Now take a look at definition of Operator Overloading: In C++ , Operator Overloading means giving additional meanings and schematics to Normal C++ operators so that we can use them with User Defined Data Types. Now look at the list of Operators that can't be Overloaded. Class Member Access / Dot Operator (.) Pointer to Member Operator (.*) Scope Resolution Operator (::) Size Of Operator ( sizeof() ) Conditional Operator (?:) There are two ways to Overload Operators in C++. They are; Using Member Function Using Friend Function IMPORTANT : For Overloading Operators ,We have to use 'operator' function. Now lets have a look at syntax for overloading operators. Syn...
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