Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ Subscript Operator [] Overloading

C++ Subscript Operator [] Overloading

C++ Operator Overloading and Function Overloading C++ Overloaded Operators and Overloaded Functions

The subscript operator [] is usually used to access array elements. Overloading this operator is used to enhance the functionality of operating on C++ arrays.

The following example demonstrates how to overload the subscript operator [].

Example

#include

<

iostream

using

namespace

std

;

const

int

SIZE

=

10

;

class

safearay

{

private

:

int

arr

[

SIZE

]

;

public

:

safearay

(

)

{

register

int

i

;

for

(

i

=

0

;

i

<

SIZE

;

i

++

)

{

arr

[

i

]

=

i

;

}

}

int

&

operator

[

]

(

int

i

)

{

if

(

i

=

SIZE

)

{

cout

<<

"

Index exceeds the maximum value

"

<<

endl

;

// return the first element

return

arr

[

0

]

;

}

return

arr

[

i

]

;

}

}

;

int

main

(

)

{

safearay

A

;

cout

<<

"

The value of A[2] is:

"

<<

A

[

2

]

<<

endl

;

cout

<<

"

The value of A[5] is:

"

<<

A

[

5

]

<<

endl

;

cout

<<

"

The value of A[12] is:

"

<<

A

[

12

]

<<

endl

;

return

0

;

}

When the code above is compiled and executed, it produces the following result:



$ g++ -o test test.cpp

$ ./test 

A[2] 的值为 : 2

A[5] 的值为 : 5

A[12] 的值为 : 索引超过最大值

0

C++ Operator Overloading and Function Overloading C++ Overloaded Operators and Overloaded Functions