Skip to content

Instantly share code, notes, and snippets.

@digitalist
Created February 20, 2019 17:42
Show Gist options
  • Select an option

  • Save digitalist/5f89e8c2f87f19820775cd721bfb1342 to your computer and use it in GitHub Desktop.

Select an option

Save digitalist/5f89e8c2f87f19820775cd721bfb1342 to your computer and use it in GitHub Desktop.
for stupids like me: overloading brackets [] (subscript) operator in C+
/*
# for stupids like me: overloading brackets [] (subscript) operator in C++
# run:
# g++ subscript_operator_overloading.cpp && ./a.out
this example works because
map (or, i.e. array) supports [] as an assignment operator, so
it works transparently, implicitly -
you don't need translate and implement assignment
*/
#include <iostream>
#include <map>
class data
{
private:
std::map<int, int> numbers; // integer array
public:
int& operator[] (int index) { return numbers[index]; } // numbers[index] ASSIGNS before return;
// returns reference to an integer (not the value of integer)
};
int main()
{
data dat;
dat[3] = 23;
std::cout << dat[3] << "\n";
std::cout << dat[4] << "\n";
std::cout << "dat[4] = 17: " << "\n";
dat[4] = 17;
std::cout << dat[4] << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment