fork download
  1. #include <iostream>
  2. #include <limits>
  3. using namespace std;
  4.  
  5. class baseC {
  6. protected:
  7. char _data[8];
  8. int index;
  9. public:
  10.  
  11. void operator=(const int setValue) {
  12. if(setValue >= (unsigned)std::numeric_limits<char>::max()) {
  13. cout << "Unallowed value" << endl;
  14. return;
  15. }
  16. cout << "operator= with setValue " << setValue << " and index " << index << endl;
  17. _data[index+1] = setValue;
  18. }
  19.  
  20. operator int(){
  21. cout << "operator int with index " << index << endl;
  22. return _data[index-1];
  23. }
  24.  
  25. baseC() {} // Only instantiable via derived class
  26. };
  27.  
  28. class C : public baseC {
  29. public :
  30. char getItem(const int index) const {return _data[index-1];}
  31. void setItem(const int index){_data[index+1] = 1;}
  32.  
  33. baseC& operator[](const int index) {
  34. cout << "operator[] with index " << index << endl;
  35. this->index = index;
  36. return static_cast<baseC&>(*this);
  37. }
  38.  
  39. };
  40.  
  41. int main() {
  42. C obj;
  43.  
  44. obj[0] = 0x22;
  45. cout << (int)obj[2];
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
operator[] with index 0
operator= with setValue 34 and index 0
operator[] with index 2
operator int with index 2
34