I would like to add an operator to a class. I currently have a GetValue()
method that I would like to replace with an []
operator.
class A { private List<int> values = new List<int>(); public int GetValue(int index) => values[index]; }
In the following example, a class called complx is defined to model complex numbers, and the + (plus) operator is redefined in this class to add two complex numbers. where () is the function call operator and [] is the subscript operator. You cannot overload the following operators: .
The subscript operator [] is normally used to access array elements. This operator can be overloaded to enhance the existing functionality of C++ arrays.
1) Overloading of [] may be useful when we want to check for index out of bound. 2) We must return by reference in function because an expression like “arr[i]” can be used an lvalue. Following is C++ program to demonstrate overloading of array index operator [].
To overload an operator, we use a special operator function. We define the function inside the class or structure whose objects/variables we want the overloaded operator to work with.
public int this[int key] { get => GetValue(key); set => SetValue(key, value); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With