fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class A {
  5. int* a;
  6.  
  7. public:
  8. A(int* a) {
  9. this->a = a;
  10. }
  11.  
  12. int& operator[](int i) {
  13. cout << "non-const" << endl;
  14. return a[i];
  15. }
  16.  
  17. const int& operator[](int i) const {
  18. cout << "const" << endl;
  19. return a[i];
  20. }
  21. };
  22.  
  23. void test(const A& a) {
  24. cout << a[0] << endl;
  25. }
  26.  
  27. int main() {
  28. int a1[] = {1, 2, 3};
  29. int a2[] = {4, 5, 6};
  30. A a(a1);
  31. const A b(a2);
  32. cout << a[0] << endl;
  33. cout << b[0] << endl;
  34. a[0] = 5;
  35. test(a);
  36. return 0;
  37. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
non-const
1
const
4
non-const
const
5