expression must be a modifiable lvalue

Sep 8, 2011 at 12:34pm
So, as an educational experience, I am making my own rudimentary Vector class using malloc (yes I know, not the wisest of moves, however, as I said, this is an educational experience.)

class definition:

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <cstdio>
#include <cstdlib>

template <typename T>
class CVector
{
	int size;
	int *Array;

	int compare (const void * a, const void * b)
	{
		return ( *(int*)a - *(int*)b );
	}

public:
	CVector(int Size)
	{
		this->Array = (T*)malloc(size*sizeof(T));
	}

	~CVector(void)
	{
		free(this->Array);
	}

	int GetSize(void)
	{
		return (sizeof(this->Array));
	}

	void Resize(int Size)
	{
		(T*)realloc(Array, ((this->size)+Size)*sizeof(T));
	}

	void sort(void)
	{
		qsort(this->Array, this->size, sizeof(T), this->compare);
	}

	T operator[](int element)
	{
		return this->Array[element]; //problem here!
	}

	int begin(void)
	{
		return 0;
	}

	int end(void)
	{
		return (sizeof(this->Array)-1);
	}
};


main:

1
2
3
4
5
6
7
8
9
10
11
int main() {
	CVector<int> test(4);

	test[0] = 1;

	cout << test[0] << endl;

	cin.get();
	
	return 0;
}


In my research, I believe from what I understand, the error lies in how I am dealing with the array. However, all I can find is help in reference to using character arrays as string ala C-style strings.

Any help would be much appreciated, thanks.
Sep 8, 2011 at 12:44pm
closed account (1vRz3TCk)
should
1
2
3
4
T operator[](int element)
{
    return this->Array[element]; //problem here!
}

be
1
2
3
4
T& operator[](int element)
{
    return this->Array[element]; 
}
Last edited on Sep 8, 2011 at 12:45pm
Sep 8, 2011 at 12:48pm
Ah, that works, however, I don't quite understand why. Would you care to explain?
Sep 8, 2011 at 1:03pm
closed account (1vRz3TCk)
Do you know about references (&)?

Basically, it returns the element of the array not a copy of the element.



PS
a Handy link that says what can and can't be overloaded and what the signature for the operator should be.
http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B
Sep 8, 2011 at 1:06pm
oh I see, sorry, this is my first time doing operator overloading at all, so I was unaware I could use the reference in this way.

Thank you kindly sir.
Topic archived. No new replies allowed.