simple example of using operator overloading in c++

 #include <stdio.h>  
 #include <stdlib.h>  
   
 //3d point  
 struct Pt3d  
 {  
      double x,y,z;  
   
      //define operator "+" for Pt3d  
      Pt3d operator+(Pt3d &p)  
      {  
           Pt3d temp = {  
                this->x + p.x,   
                this->y + p.y,   
                this->z + p.z,   
           };  
           return temp;  
      }  
 };  
   
   
 int _tmain(int argc, _TCHAR* argv[])  
 {  
      Pt3d a, b, c;  
      a.x = 1.0;  
      a.y = 1.1;  
      a.z = 1.2;  
   
      b.x = 2.0;  
      b.y = 2.1;  
      b.z = 2.2;  
        
      //by only using this, you can get addition of point a and b  
      c = a + b;  
        
      //let's check it  
      //result should be 3.00, 3.20, 3.40  
      printf("coordinate of c in a, y, z is as follow:\n");  
      printf("%.2f, %.2f, %.2f \n", c.x, c.y, c.z);  
      return 0;  
 } 
 
result:
 
3.00, 3.20, 3.40 

No comments