Mega Code Archive

 
Categories / C++ Tutorial / Operator Overloading
 

Design the operator[ ]( ) function in such a way that the [ ] can be used on both the left and right sides of an assi

#include <iostream> using namespace std;     class MyClass {   int a[3]; public:   MyClass(int i, int j, int k) {     a[0] = i;     a[1] = j;     a[2] = k;   }   int &operator[](int i) { return a[i]; } };     int main() {   MyClass ob(1, 2, 3);       cout << ob[1]; // displays 2   cout << " ";       ob[1] = 25;    // [] on left of =       cout << ob[1]; // now displays 25       return 0; }