Created
February 20, 2019 17:42
-
-
Save digitalist/5f89e8c2f87f19820775cd721bfb1342 to your computer and use it in GitHub Desktop.
for stupids like me: overloading brackets [] (subscript) operator in C+
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| # 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