在 C++ 中過載陣列索引運算子 []


運算子過載在面向物件程式語言特性中扮演著重要角色。運算子過載是一種編譯時或靜態多型性。

演算法

Begin
   Create a class Arr and declare size of array.
   Inside the class, initialize all the elements by using for loop.
   Print the all elements.
End.

示例程式碼

 即時演示

#include <iostream>
#include <stdlib.h>
using namespace std;
const int M = 7;
class Arr {
   private:
   int A[M];
   int size;
   public:
   Arr(int s, int v) {
      if(s>M) {
         cout<<endl<<"This is beyond maximum size";
         exit(1);
      }
      size = s;
      for(int i=0;i<size;i++)
         A[i] = v;
   }
   int& operator[](int i) {
      if( (i<0) || (i>=size) ) {
         cout<<endl<<"Error: Array out of bound";
         exit(1);
      }
      return A[i];
   }
};
int main() {
   int i=0;
   Arr a(7,0);
   for(i=0;i<7;i++)
      a[i] = i*10;
   cout<<"Array elements are:"<<endl;
   for(i=0;i<7;i++) {
      int val = a[i];
      cout<<val<<endl;
   }
   return 0;
}

輸出

Array elements are:
0
10
20
30
40
50
60

更新於:2019 年 7 月 30 日

381 次瀏覽

開啟您的職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.