Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Operator Overloading refers to giving the normal C++ Operators, such as +,*,<= etc., additional meanings when they are applied to user defined data types. simply defined as to create new definitions for operators. 2. Data type conversions is closely connected with operator overloading. Syntax : <ret.datatype> operator <operator name>() { ----}
class
4. Use the operator in the main() function
All the operators can be overloaded using friend function except () [] -> and =. These operators must be defined by using a member function.
ASSIGNMENT OPERATOR OVERLOADING RULES : The operator function for the assignment operator are inherited by any derived class. Friend functions cannot be used to overload the assignment operator
are
- * | _ != -+ *= !=
|| &= &&
The procedence and associativity of an operator cannot be altered The syntax of overloaded operator is same as ordinary operators The number of operands that an operator takes cannot be changed
++c1;
c2=++c1; cout<<"\n c1 ="<<c1.get_count(); cout<<"\n c2 ="<<c2.get_count(); }
OUTPUT :
C1 = 0 C2 = 0 C1 = 2 C1 = 2
cout<<"\n Enter inches :"; cin>>inches; } void show() { cout<<feet<<inches<<"\n"; } Distance operator +(Distance); };
Distance Distance ::operator +(Distance d2) { int f=feet+d2.feet; float i=inches+d2.inches; return Distance(f,i); } void main() OUTPUT : { Enter feet : 5 Distance d1,d3,d4; Enter inches : 4.4 Distance d2(11,6.25); d1 = 5 4.4 d1.get(); d2 = 11 6.25 d3=d1+d2; d3 = 16 10.65 d4=d1+d2+d3; d4 = 32 21.299999 cout<<"\n D1= ";d1.show(); cout<<"\n D2= ";d2.show(); cout<<"\n D3= ";d3.show(); cout<<"\n D4= ";d4.show(); }
void operator -(minus &m) { m.a=-m.a; m.b=-m.b; } void main() { minus m; m.get(100,50); m.display(); -m; m.display(); }
OUTPUT :
-100 -50
cout<<a1[i]<<"\t";} } OUTPUT :
1 2 3 4 5
void accept() { cout<<"\n Enter 2 Values"; cin>>a>>b; } }; void main() { operations x; x.accept(); x.c=x.a+x.b; cout<<x.c<<endl; x.d=x.a-x.b; cout<<x.d<<endl; x.e=x.a*x.b; cout<<x.e<<endl; }
OUTPUT :
Overloading
an increment & Decrement operator has two forms, the Prefix and Postfix form.
EXERCISES
1. Define Operator Overloading?
2. List the Operators that can be overloaded? 3. Explain the process of overloading an unary minus operator with friend functions? 4. Explain the process of overloading an binary plus operator with friend functions? 5. Explain the process of overloading Relational & Logical operator with an example? 6. Explain the process of overloading member access operator? 7. State the important points to be noted while using Operator Overloading?