Sunday, June 11, 2017

Operator Overloading III

/*This code was written by A. El-Gadi of Tripoli University for educational purposes. It illustrates the importance of implementing a const index operator. For any questions  and discussion use the comment section below.*/

#include <iostream>

using namespace std;

class Indexer{
    private:
    double a0,a1,a2,a3,a4;

    public:
  
    Indexer():a0(0),a1(0),a2(0),a3(0),a4(0){};  
    double& operator [](int index){
            if(index<=0){return a0;}
            else{
                if(index>=4){return a4;}
                else{
                    switch(index){
                      
                        case 1: return a1;
                        case 2: return a2;
                        case 3: return a3;
                        }
                    }
            }
        }

    const double& operator [](int index) const {
            if(index<=0){return a0;}
            else{
                if(index>=4){return a4;}
                else{
                    switch(index){
                      
                        case 1: return a1;
                        case 2: return a2;
                        case 3: return a3;
                        }
                    }
            }
        }
};

double sumelements(const Indexer idr){double sum=0; for(int i;i<5;i++){sum=sum+idr[i];}; return sum;}

int main(){
Indexer indr;

indr[0]=11; indr[1]=22; indr[2]=33; indr[3]=44; indr[4]=55;
double g=sumelements(indr);//Compilation error if const index operator is not implemented because sumelements will attempt to use a const index operator

const Indexer cindr;
double h=cindr[0];//Compilation error if const index operator is not implemented because cinder is const.


return 0;
}

1 comment:

  1. El Yucateco Hotel & Casino - Mapyro
    Your Central 군포 출장안마 Market 대구광역 출장샵 spot 대구광역 출장안마 is where every Mexican seafood lover gets a kick 상주 출장안마 with the El Yucateco Salsa Picante Hot 전주 출장마사지 Sauce. El Yucateco Salsa Picante Hot

    ReplyDelete