Page 1 of 1

C++ operator overloading

Posted: Fri Aug 26, 2011 5:41 pm
by adamemanuel
Hey geeks,

Have a n00bish question, I'm overloading the [] operator to implement an array like class.
It works fine, my problem arises when I've a pointer to the object.

MyClass c;
c[5] works fine

However
MyClass *c = new MyClass();
*c[5] will not work since the precedence of [] is higher than that of *
So I've to write it as
(*c)[5] which is not looking good for me :) any solution to overcome this.

Re: C++ operator overloading

Posted: Fri Aug 26, 2011 10:10 pm
by schilds
If you like solutions which are more painful than the original problem:

Code: Select all

template< typename C, typename T >
class CollectionPointer
{
private:
        C * collection;

public:
        CollectionPointer(C * collection)
        : collection(collection)
        {
        }

        T& operator[](int i)
        {
                return (*collection)[i];
        }

        C& operator*()
        {
                return *collection;
        }

        C* operator->()
        {
                return collection;
        }

        void clean(){
                delete collection;
        }
};

#include <iostream>
#include <vector>

typedef CollectionPointer< std::vector<int>, int > MyVector;

int main()
{
        MyVector numbers(new std::vector<int>());
        numbers->push_back(0);
        std::cout << numbers[0] << std::endl;
        numbers.clean();
}
Tada!

Re: C++ operator overloading

Posted: Sat Aug 27, 2011 6:31 pm
by adamemanuel
That's what I was trying to achive:

Code: Select all

class MyArr{
public:
	MyArr();
	~MyArr();
	uint8_t& operator[](const int);
private:
	uint8_t *arr;
	unsigned int size;
	void init();
};

Code: Select all

MyArr::MyArr(){
	size = 1000;
	init();
}
MyArr::~MyArr(){
	delete[] arr;
	size = 0;
}
void MyArr::init(){
	arr = new uint8_t[size];
}
uint8_t& MyArr::operator[](const int i){
	if(){
                      // some checkings
	}
	return arr[i];
}

Code: Select all

int main(){
	MyArr m;
	m[2] = 5;   // <--- works fine

	MyArr *k = new MyArr();
	(*k)[2] = 3;   // <--- I want to be able to just use *k[2] = 3 or k[2] = 3 instead !!!!
	uint8_t y = (*k)[2];
	std::cout << (int)y << std::endl;
	return 0;
}