overloading array[1..8] operator

josh BAUER 166 Reputation points
2020-12-28T19:31:40.497+00:00

How to overload [stNumber..snNumber] operator which I
would use in following way

array[3..7]

??

Developer technologies | C++
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jeanine Zhang-MSFT 11,356 Reputation points Microsoft External Staff
    2020-12-29T03:28:45.263+00:00

    Hi,

    According to your description, if you want to overload [Subscript Operator ?

    Here is a demo, I suggest you could refer to :

    #include <iostream>  
    using namespace std;  
    const int SIZE = 9;  
      
    class Array {  
    private:  
    	int arr[SIZE];  
      
    public:  
    	Array() {  
    		register int i;  
    		for (i = 0; i < SIZE; i++) {  
    			arr[i] = i;  
    		}  
    	}  
      
    	int &operator[](int i) {  
    		if (i > SIZE) {  
    			cout << "Index out of bounds" << endl;  
    			// return first element.  
    			return arr[0];  
    		}  
      
    		return arr[i];  
    	}  
    };  
      
    int main() {  
    	Array A;  
      
    	cout << "Value of A[3…7] : " << A[3]<<","<< A[4] << "," << A[5] << "," << A[6] << "," << A[7] << endl;  
      
    	return 0;  
    }  
    

    Best Regards,

    Jeanine


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.