fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct myArray;
  5.  
  6. class proxy {
  7. myArray &array;
  8. int index;
  9. public:
  10. proxy(myArray &_array, int _index)
  11. : array(_array)
  12. , index(_index) {
  13. }
  14. proxy& operator=(int value);
  15. operator int() const;
  16. };
  17. struct myArray {
  18. int data[100];
  19. proxy operator[](int index) {
  20. return proxy(*this, index);
  21. }
  22. };
  23.  
  24. proxy& proxy::operator=(int value) {
  25. cout << "Asigning " << value << " to element " << index << endl;
  26. array.data[index] = value;
  27. return *this;
  28. }
  29.  
  30. proxy::operator int() const {
  31. cout << "Reading element at " << index << endl;
  32. array.data[index];
  33. }
  34.  
  35. int main() {
  36. myArray a;
  37. a[5] = 123;
  38. a[8] = 321;
  39. int x = a[5];
  40. return 0;
  41. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
Asigning 123 to element 5
Asigning 321 to element 8
Reading element at 5