c++ - Why array indexing not showing commutative behavior in this program? -


i know array indexing commutative in both c & c++, a[i] same i[a] , have same effect i[a] , both valid. wrote following program fails compile when use i[intob] instead of intob[i].

#include <iostream> #include <cstdlib> using std::cout; template<class t>class atype {     t* a;     int size;     public:         atype(int n)         {             size=n;             a=new t[size];             for(auto i=0;i<size;i++)                 a[i]=i;         }         ~atype()         {             delete[] a;         }         t& operator[](int i); }; template<class t> t& atype<t>::operator[](int i) {     if(i<0 || i>size)     {         cout<<"\nindex value of ";         cout<<i<<" out of bounds.\n";         exit(1);     }     return a[i];   // i[a] works fine here. } int main() {     int i,n;     cout<<"enter value of n: ";     std::cin>>n;     atype<int> intob{n};     atype<long int> longintob{n};     cout<<"integer array: ";     for(i=0;i<n;i++)         intob[i]=i;      for(i=0;i<n;i++)         cout<<i[intob]<<' ';    // oops compiler error why???     cout<<'\n';      cout<<"long integer array: ";     for(i=0;i<n;i++)         longintob[i]=i;     for(i=0;i<n;i++)         cout<<longintob[i]<<' ';     longintob[15]=123; } 

i getting following compiler error.

[error] no match 'operator[]' (operand types 'int' , 'atype')

but if write i[a] in overloaded [] operator function works fine. why?

is there solution exist access array elements using i[intob]?

tell me if wrong somewhere & understanding incorrectly.

the indexing operator not commutative.

it helps if understand array (or pointer) a , index i a[i] equivalent *(a + i). commutative bit comes addition, because *(a + i) equal *(i + a) leads i[a] being valid.


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -