overloading [] operator

Hi, im having trouble overloading the [] operator.

Heres what im trying to test:
1
2
3
4
5
6
7
8
9
10
void test() {
	cout << "3. Array declared with two integers: IntArray c(6, 8);" << endl << endl;
	csis << "3. Array declared with two integers: IntArray c(6, 8);" << endl << endl;
	IntArray c(6, 8); // three elements, indexed 6 to 8
	for (int i = c.low(); i <= c.high(); i++)
		c[i] = i * 10;
	c.setName("c");
	cout << c << endl;
	wait();
}


the part where im having is "c[i] = i * 10;". how would i overload the [] correctly?
i did abit of reading and i came out with

1
2
3
	int& IntArray::operator[](int i) {
		return i;
	}


but when i run the program, it outputs
1
2
3
4
3. Array declared with two integers: IntArray c(6, 8);

c[6] = 6 c[7] = 7 c[8] = 8
Press any key to continue.

its not multiplying the value by 10 ?

if this helps, heres what i did for the << operator
1
2
3
4
5
ostream& operator<<(ostream& os, IntArray& a) {
	for (int i = a.low(); i <= a.high(); i++)
		os << a.getName() << "[" << i << "] = " << a[i] << " ";
	return os;
}
Last edited on
seiyakun wrote:
1
2
3
	int& IntArray::operator[](int i) {
		return i;
	}
This is wrong for multiple reasons (one of which is returning a reference to a temporary). You need to return a reference to the data inside your class. Your class does contain an array of some kind, does it not?
1
2
3
	int& IntArray::operator[](int i) {
		return i;
	}


'i' is your index, right? So if i==3 you would want it to return whatever value is in position [3] in your array.

That's not what you're returning here. You are returning the index itself. So if i==3, you will return 3, regardless of what is actually in your array.



What's worse, is you're returning a reference to a local variable, which your compiler probably should be yelling at you about. This is very dangerous because the reference becomes bad as soon as the function exits.




Long story short - you don't want to return i. You want to use i to figure out which element to return.
so what you guys are saying is that i should be returning something like
"return a[i];" where i variable is passed through the []operator, so it returns the element.

but how do i do that if the array name and size isnt fixed?

like i have to test others too like:
1
2
3
4
5
6
7
8
9
10
11
void test2() {
	cout << "2. Array declared with two integers: IntArray b(-3, 6);" << endl << endl;
	csis << "2. Array declared with two integers: IntArray b(-3, 6);" << endl << endl;
	IntArray b(3, 6);
	for (int i = b.low(); i <= b.high(); i++)
		b[i] = i * 10;
	b.setName("b");
	cout << b << endl;
	csis << b << endl;
	wait();
]


the purpose of this assignment is being able to declare integer arrays of any size with automatic range checking of indices. and also being able to assign entire arrays to each other, compare arrays for equality/inequality, and add two arrays together.
Last edited on
but how do i do that if the array name and size isnt fixed?


None of that matters.

You have an 'IntArray' class. That class must have the array data stored somewhere, right?. That is the data you use.
yes, i declared the int array as "a[100]" in private; but im not sure if that is the correct way to handle it.
Unfortunately, your assignment probably wants you to use dynamic memory.
ahh, i see. i did some reading about dynamic arrays and i have to use pointers? i tried, but i couldn't figure it out.
Try watching a video of someone explaining it then

https://www.youtube.com/watch?v=C_hYF7YG_yQ&index=24&list=PL2DD6A625AD033D36&ab_channel=CodingMadeEasy

Lots of more hits on youtube/google.
> i did some reading about dynamic arrays and i have to use pointers?

Read up on vectors https://www.mochima.com/tutorials/vectors.html and use a vector instead.

Something along these lines:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <vector>

struct int_array
{
    int_array( int low, int high ) : low_index(low), high_index(high)
    {
        if( high_index < low_index ) high_index = low_index ;
        data.resize( high_index - low_index + 1 ) ;
    }
    // implicitly declared copy/move constructor, copy/move assignment, destructor (vector is copyable and movable)

    int low() const { return low_index ; }
    int high() const { return high_index ; }

    // vector<>::at() provides bounds checked access
    int& operator[] ( int pos ) { return data.at(pos-low_index) ; }
    const int& operator[] ( int pos ) const { return data.at(pos-low_index) ; }

    // vector is EqualityComparable. http://en.cppreference.com/w/cpp/container/vector/operator_cmp
    bool operator== ( const int_array& that ) const { return low_index == that.low_index && data == that.data ; }
    bool operator!= ( const int_array& that ) const { return !( *this == that ) ; }

    // etc

    private:
        int low_index ;
        int high_index ;
        std::vector<int> data ;
};
Well of course... using a vector kind of defeats the point of writing a dynamic array class... since vector IS a dynamic array class.

Might as well just do:

 
typedef std::vector<int>  int_array;



EDIT:

Well... I guess vector doesn't have ALL the requirements he needs. =P
Last edited on
Topic archived. No new replies allowed.