Im trying to overload the [] operator in c++ so that I can assign / get values from my data structure like a dictionary is used in c#:
Array[“myString”] = etc.
Is this possible in c++?
I attempted to overload the operator but it doesnt seem to work,
Record& MyDictionary::operator[] (string& _Key)
{
for (int i = 0; i < used; ++i)
{
if (Records[i].Key == _Key)
{
return Records[i];
}
}
}
Thanks.
Your code is on the right track – you’ve got the right function signature – but your logic is a bit flawed. In particular, suppose that you go through this loop without finding the key you’re looking for:
If this happens, your function doesn’t return a value, which leads to undefined behavior. Since it’s returning a reference, this is probably going to cause a nasty crash the second that you try using the reference.
To fix this, you’ll need to add some behavior to ensure that you don’t fall off of the end of the function. One option would be to add the key to the table, then to return a reference to that new table entry. This is the behavior of the STL
std::mapclass’soperator[]function. Another would be to throw an exception saying that the key wasn’t there, which does have the drawback of being a bit counterintuitive.On a totally unrelated note, I should point out that technically speaking, you should not name the parameter to this function
_Key. The C++ standard says that any identifier name that starts with two underscores (i.e.__myFunction), or a single underscore followed by a capital letter (as in your_Keyexample) is reserved by the implementation for whatever purposes they might deem necessary. They could#definethe identifier to something nonsensical, or have it map to some compiler intrinsic. This could potentially cause your program to stop compiling if you move from one platform to another. To fix this, either make theKlower-case (_key), or remove the underscore entirely (Key).Hope this helps!