Indexer (programming)
In object-oriented programming, an indexer allows instances of a particular class or struct to be indexed just like arrays. It is a form of operator overloading.
Implementations
C++
In C++ one can emulate indexing by overloading the operator. The expression translates to a call to the user-defined function as. Here is an example,struct vector ;
- include
C#
Indexers are implemented through the get and set accessors for the. They are similar to properties, but differ by not being 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 parameter.Example 1
public class Vector
Example 2
Here is a C# example of the usage of an indexer in a class:class Family
Usage example:
void Main
In this example, the indexer is used to get the value at the nth position, and then to get the position in the list referenced by its value.
The output of the code is:
John is the member number 0 of the doeFamily
Jane is the member number 1 of the doeFamily
PHP
In PHP indexing can be implemented via the predefined interface,class Vector implements ArrayAccess
$vector = new Vector;
for $vector = $i + 1;
for print "\n";
Python
In Python one implements indexing by overloading the and methods,import array
class Vector:
def __init__:
self.size = n
self.data = array.array
def __getitem__:
return self.data
def __setitem__:
self.data = value
vector = Vector
for i in range:
vector = i + 1
for i in range:
Rust
Rust provides the trait.use std::ops::Index;
enum Nucleotide
struct NucleotideCount
impl Index
let nucleotide_count = NucleotideCount ;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Smalltalk
In Smalltalk one can emulate indexing by defining the and instance methods. For example, in GNU Smalltalk,Object subclass: vector
vector class extend ]
vector extend ]
vector extend ]
vector extend ]
vector extend ]
v:=vector new: 3
1 to: do:
1 to: do: