Indexer (programming): Difference between revisions

Content deleted Content added
Dmt137 (talk | contribs)
m C sharp: added csharp "vector" example
Dmt137 (talk | contribs)
Implementation: PHP implementation
Line 2:
In [[object-oriented programming]], an '''indexer''' allows instances of a particular class or struct to be indexed just like arrays.<ref>{{cite web|access-date=2011-08-01 |author=jagadish980 |date=2008-01-29 |website=SURESHKUMAR.NET FORUMS |title=C# - What is an indexer in C# |url=http://forums.sureshkumar.net/vb-asp-net-interview-technical-questions/16320-c-what-indexer-c.html |archive-url=https://web.archive.org/web/20090922193214/http://forums.sureshkumar.net/vb-asp-net-interview-technical-questions/16320-c-what-indexer-c.html |archive-date=September 22, 2009 }}</ref> It is a form of [[operator overloading]].
 
== ImplementationImplementations ==
=== 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>.
Line 98:
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 {{python|ArrayAccess}} interface<ref>{{cite web|url=https://www.php.net/manual/en/class.arrayaccess.php|title=PHP ArrayAccess interface}}</ref>,
<syntaxhighlight lang="php">
<?php
class vector implements ArrayAccess {
function __construct(int $n){
$this->size=$n;
$this->data=array_fill(0,$n,0);
}
public function offsetGet($offset): mixed{
return $this->data[$offset];
}
public function offsetSet($offset, $value): void{
$this->data[$offset] = $value;
}
public function offsetExists($offset):bool{}
public function offsetUnset($offset):void{}
}
$v=new vector(3);
for($i=0;$i<$v->size;$i++)$v[$i]=$i+1;
for($i=0;$i<$v->size;$i++)print "{$v[$i]}\n";
?>
</syntaxhighlight>
 
=== Python ===