Sunday, 4 March 2012

Method Overloading


Operator Overloading
It is similar to method overloading
except that the  method name is now symbolic
It is possible in C++ and C#
Some rules about operator overloading
1 Precedence Order cannot be changed
e.g. 2+3*5
multiply has a higher precedence than addition
hence result = 17 instead of 25
2 Arity (number of parameters) of the opeerator cannot be changed
e.g.
+ is a binary operator i.e. 2 + 3 OR +(2,3) =>  add(2,3)
it cannot add three values
3 new operator symbols cannot be defined
//code
class Distance{
 private int miles, yards, feet;
 public Distance(int m, int y, int f){
  miles = m;
  yards = y;
  feet = f;
 }
 Distance +(Distance d){
  Distance t = new Distance (0,0,0);
  t.feet = this.feet + d.feet;
  if(t.feet>=3)
  { t.yards+=1; t.feet-=3; }
  t.yards += this.yards + d.yards;
  if(t.yards>1760)
  {
   t.miles +=1;
   t.yards -= 1760;
  }
  t.miles+= this.miles + d.miles;
  return (t);
 } 
}
Method
Constructor
Desctructor
Overloaded Operator
Method overload

 

No comments:

Post a Comment