Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การโอเวอร์โหลดออเปอเรเตอร์ดัชนีอาร์เรย์ [] ใน C++

การโอเวอร์โหลดออเปอเรเตอร์มีบทบาทสำคัญในคุณสมบัติของภาษาเชิงวัตถุ (OOP) เป็นประเภทหนึ่งของ polymorphism แบบคอมไพล์ไทม์ (static polymorphism)

อัลกอริธึม

  1. สร้างคลาส Arr และประกาศขนาดอาร์เรย์
  2. ภายในคลาส เริ่มต้นองค์ประกอบทั้งหมดด้วยลูป for
  3. โอเวอร์โหลดออเปอเรเตอร์ [] เพื่อเข้าถึงอาร์เรย์พร้อมตรวจสอบขอบเขต (bounds checking)
  4. พิมพ์องค์ประกอบทั้งหมด

โค้ดตัวอย่าง

#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]; // คืน reference เพื่อให้ assign ได้ (l-value)
    }
};

int main() {
    int i = 0;
    Arr a(7, 0);
    for(i = 0; i < 7; i++)
        a[i] = i * 10; // ใช้ operator[] ในการ assign

    cout << "Array elements are:" << endl;
    for(i = 0; i < 7; i++) {
        int val = a[i]; // ใช้ operator[] ในการอ่าน
        cout << val << endl;
    }
    return 0;
}

ผลลัพธ์

Array elements are:
0
10
20
30
40
50
60

จุดสำคัญ: operator[] คืน int& (reference) ไม่ใช่ int เพื่อให้สามารถใช้เป็น l-value ได้ (เช่น a[i] = 10) การตรวจสอบขอบเขต (bounds checking) ช่วยป้องกัน buffer overflow ซึ่งอาร์เรย์ดิบของ C++ ไม่ทำให้