Indexer (programming): Difference between revisions

Content deleted Content added
Dmt137 (talk | contribs)
added c++ example
Line 3:
 
== Implementation ==
=== C++ ===
In C++ one can emulate indexing by overloading the {{c++|[]}} operator. Specifically, the expression {{c++|a[b...]}} translates to a call to the user-defined function {{c++|operator[]}} as {{c++|(a).operator[](b...)}}<ref>{{cite web|url=https://en.cppreference.com/w/cpp/language/operators|title=cppreference}}</ref>.
 
==== Example ====
<syntaxhighlight lang="c++">
struct vector{
int size; double* data;
vector(int n){size=n; data=new double[n]();}
~vector(){size=0;delete[] data;}
double& operator[](int i){return data[i];}
};
#include<iostream>
int main(){
vector v(3);
for(int i=0;i<v.size;i++) v[i]=i+1;
for(int i=0;i<v.size;i++) std::cout << v[i] << "\n";
return 0;
}
</syntaxhighlight>
 
=== C sharp ===
Indexers are implemented through the get and set [[Mutator method|accessor]]s for the {{C_sharp|operator[]}}. They are similar to [[Property (programming)|properties]], but differ by not being [[Static method|static]], and the fact that indexers' accessors take parameters. The get and set accessors are called as methods using the parameter list of the indexer declaration, but the set accessor still has the implicit {{C_sharp|value}} parameter.
 
==== Example ====
Here is a C# example of the usage of an indexer in a class:
<ref>{{cite web
Line 61 ⟶ 82:
John is the member number 0 of the doeFamily
Jane is the member number 1 of the doeFamily
 
 
 
== See also ==