Kumpulan Program Sederhana

Jumat, 01 April 2011

Operator Overloading

           The basic concept for the conduct of operator overloading is to define a function, which is known as the function of the operator. This function is used to create the keywordoperator. Function operators mostly serves as a member (member function) of a class.There is a difference between writing a function for the operator functions for themanufacture of which is a class member and non-members. Here is a common form ofmaking the operator functions that are members of a class

           return_ type class_name:: operator # (parameter list) {/ / operation to be performed}

           In the general form above class_name is the name of the owner class functions. while the sign of # the above serves as a placeholder, which means this is where we definethe operator what will we Overload. If we want to overload the operator +, then the writing of its functions is the operator +While the general form of making a function that is not a member of the class (which isusually the friend function) is the same as defining the usual functions, as follows

          return_type operator # (parameter_list) {/ / operation to be performed}


Operators that can not be in Overload
          although C + + has given us freedom to do overload, but there are some operators whoare not authorized to perform overload. For example:( . .* :: ?:) in addition we are also not allowed to perform overload of preprocessor symbols,namely # and # #

The following are the operators that we can overload:
          a. Unary Operators
               + - * & ~ ! ++ -- -> ->*
          b. Binary Operators
               + - * / % ^ & | << >> += -= *= /= %= |= <<= >>= < <= > >= == != && || , [] () new new [ ]                
               delete delete [ ]

Perform a binary operator overload

  Overload Operator +
Here we will create a program in which there are overloaded operators plus (+) so the operator can add two values ​​of type object.

#include <cstdlib>
#include <iostream>

using namespace std;
//create a class POINT
class TITIK {
      int X,Y;
      public :
      //create function constructor for the class POINT
             TITIK (int XX, int YY){
                   X=XX;
                   Y=YY;
                   }
   //create function show XY
                   void showXY(){
                        cout<<"nilai X: "<<X<<endl;
                        cout<<"nilai Y: "<<Y<<endl;
                        }
//declaring that reverse the function object operator POINT
                        TITIK TITIK ::operator +(TITIK P);
                        };
//implementation of the above operator function
                        TITIK TITIK ::operator +(TITIK P){
                              return TITIK (P.X+X, P.Y+Y);
                              }
//The main function           
int main(int argc, char *argv[])
{
    //do the instantiation of the class POINT
    TITIK A(4,2);
    TITIK B(6,3);
    
    //display the X and Y values ​​contained in objects A and B
    A.showXY();
    cout<<endl;
    B.showXY();
    cout<<endl;
    
    //add objects A and B and save it to the object C
    TITIK C=A+B;

    //displays the value of X and Y contained in the object C
    C.showXY();
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

view results

nilai X: 4
nilai Y: 2

nilai X: 6
nilai Y: 3

nilai X: 10
nilai Y: 5

         as we saw above that the operator + can be used to add two objects of type POINT. By default, this operation would not be allowed by the compiler. But by doing terhadpaoverloaded operators, then we can do it.

Overload unary operator

     Overload operator + +
         By default, in c + + operator increments (+ +) is used to increase the value of one to avariable of type integer, floating-point numbers and characters. But here we will do theoverload on the operator so that it can work for the type of object. The class will be takenas an example here is the point (which has the data X and Y). In this example, eachincrement objects X and Y values ​​of the object will automatically be increased by one


#include <cstdlib>
#include <iostream>

using namespace std;
//create a class POINT
class TITIK {
      int X,Y;
      public :
             
      //create function constructor for the class POINT
             TITIK (int XX, int YY){
                   X=XX;
                   Y=YY;
                   }
   //create function show XY
                   void showXY(){
                        cout<<"nilai X: "<<X<<endl;
                        cout<<"nilai Y: "<<Y<<endl;
                        }
      //making functions for the pre-increment operator
                              TITIK operator ++(){
                              X += 1;
                              Y += 1;
                              return *this;
                              }
      //making functions for the post-increment operator
                              TITIK operator ++(int){
                              X += 1;
                              Y += 1;
                              return *this;
                              }
};
//ThE main function         
int main(int argc, char *argv[])
{
    //do the instantiation of the class POINT
    TITIK A(4,2);
    //pre-increment to the object A
    cout<<"pre-increment untuk objek A"<<endl;++A;
    //displays the value of X and Y contained in the object A
    A.showXY();
    cout<<endl;
    
    //do the instantiation of the class POINT
    TITIK B(6,3);
    //pre-increment to the object B
    cout<<"pre-increment untuk objek B"<<endl;B++;
    //displays the value of X and Y contained in the object B
    B.showXY();

    system("PAUSE");
    return EXIT_SUCCESS;
}

view result

pre-increment untuk object A
nilai X:5
nilai Y:3

pre-increment untuk object B
nilai X:7
nilai Y:4



Overload of special operators

      Overload operator delete
           This time we will discuss about the overload for operator delete through a simpleexample program. A common form creation operator to operator delete functions,namely                      void operator delete (void * p) {/ / allocate memory pointed to by pointer p}
we will do the overload on the operator delete so it can be used specifically for the classPOINT.
#include <cstdlib>#include <iostream>#include <new>using namespace std;//create a class POINTclass TITIK {      int X,Y;      public :                    //create function constructor for the class POINT             TITIK (int XX, int YY){                   X=XX;                   Y=YY;                   }    //create function show XY                   void showXY(){                        cout<<"nilai X: "<<X<<endl;                        cout<<"nilai Y: "<<Y<<endl;                        }       //create function operator to new operator                              void *operator new(size_t size){                              void *P;                              cout<<"operator new yang didefinisikan sendiri"<<endl;                              //perform memory allocation       P = malloc (size);       //if that fails, throw expression bad_alloc       if (!P){       bad_alloc BA;       throw BA;       }                              return P;                              }       //create function operator to operator delete                              void operator delete(void *P){       cout<<"operator delete yang didefinisikan sendiri"<<endl;       free (P);                              }         };
//ThE main function         int main(int argc, char *argv[]){    //declare pointer PT who will appoint the type POINT    TITIK *PT;    //perform allocation with new operator    try {         PT = new TITIK (4,8);    //displays the value of X and Y    PT->showXY();}    catch (bad_alloc E) {        cout<<"Alokasi untuk PT gagal"<<endl;    return 1;    //allocate memory    delete PT;    //declare a pointer that will point to type int    int *PI;    PI = new int;    *PI = 200;
    cout<<"\nNilai *PI : "<<*PI<<endl;
    system("PAUSE");    return EXIT_SUCCESS;}

view result

operator new yang didefinisikan sendiri
nilai X: 4
nilai Y: 8
operator delete yang didefiniskan sendiri

Nilai *PI : 200

                    when we use delete operator to a pointer to the class POINT, then the screen will displaythe text "operator delete yang didefinisikan sendiri". whereas for the removal of PI pointerthat points to a type int, delete operators that are used still contained the originaloperator in c + +.
                



foot note: Pemograman c++,2007, Budi Raharjo




            



Tidak ada komentar:

Posting Komentar