fork(3) download
  1. /*****************************************************************
  2. Name : 重載下標符號 const 函式
  3. Date : 2017/02/20
  4. By : CharlotteHonG
  5. Final: 2017/02/20
  6. *****************************************************************/
  7. #include <iostream>
  8. #include <vector>
  9. #include <numeric>
  10.  
  11. using namespace std;
  12.  
  13. class Arr{
  14. public:
  15. // 建構子
  16. Arr(int len): arr(len){
  17. iota(arr.begin(),arr.end(),1);
  18. }
  19. // 重載下標符號
  20. int & operator[](size_t idx){
  21. return arr[idx];
  22. }
  23. const int & operator[](size_t idx) const{
  24. cout << "**Const**" << endl;
  25. return arr[idx];
  26. }
  27. private:
  28. vector<int> arr;
  29. };
  30.  
  31. void pri(const int & num){
  32. cout << "num=" << num << endl;
  33. }
  34. int main(){
  35. Arr a(5);
  36. pri(a[0]);
  37. return 0;
  38. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
num=1