I am new to C++ and I am sorry because of this question, but it is a struggle. If someone could help me to distinguish following lines, I would me grateful.
char& operator [](int); // write (why with reference?)
char operator [](int) const; //read (why without a reference?)
char const &operator[](int) const; // what is the difference compared to the previous line?
const char *& operator[] (const int* ); // is this also possible?
Operator overloading allows C/C++ operators to have user-defined meanings on user-defined types (classes).
An overloaded operator (except for the function call operator) cannot have default arguments or an ellipsis in the argument list. You must declare the overloaded = , [] , () , and -> operators as nonstatic member functions to ensure that they receive lvalues as their first operands.
[13.6] Can I overload operator== so it lets me compare two char[] using a string comparison? No: at least one operand of any overloaded operator must be of some class type.
Function overloading means using a single name and giving more functionality to it. Operator overloading means adding extra functionality for a certain operator. When an operator is overloaded, the operator has different meanings, which depend on the type of its operands.
You might want to read an overview of Operator overloading .
So, to recap some applicable points:
operator[]
is always non-static unary member-function.const
-qualified overloads can either return a const
reference or a copy, to provide read-only access to the same elements.
const
-reference if the element cannot be dynamically generated, especially if it's not trivially and cheap to copy.BTW: You really want to have the const
and non-const
members be analogous, so the non-const
can be a simple inline-function delegating to the other with the appropriate const_cast
.
(Don't do it the other way around, that would not be quite allowed, or safe.)
Regarding your last line, that indexes with a pointer to const int
, and returns a reference to a pointer to const char
.
That is a seriously odd return-value and index, though if you have a valid use for it, why not?
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