Reputation: 101
I have a class which has overloaded the array index operator[]. Now I have to create a pointer to that class, How can I use index operator [] using pointer to the class. Following code works fine, but if i un-comment the basicVector * a = new basicVector(10) line and put -> in place of ., I get errors.
Please see this link for compiler settings and code.
#include <iostream> // std::cout
#include <queue> // std::queue
#include <string>
#include <string.h>
#include <stdint.h>
#include <vector>
using namespace std;
class basicVector
{
private:
uint32_t array_size;
uint8_t * array;
public:
basicVector(uint32_t n);
~basicVector();
uint32_t size();
uint8_t * front();
uint8_t& operator[](uint32_t i);
};
basicVector::basicVector(uint32_t n)
{
array_size = n;
array = new uint8_t[n];
}
basicVector::~basicVector()
{
delete [] array;
}
uint32_t basicVector::size()
{
return array_size;
}
uint8_t * basicVector::front()
{
return array;
}
uint8_t& basicVector::operator[](uint32_t i)
{
return array[i];
}
int main ()
{ //basicVector * a = new basicVector(10);
basicVector a(10);
cout <<a.size()<<endl;
for(uint8_t i=0; i < a.size(); i++)
{ a[i] = i+50; //how to do this correctly when "a" is pointer?
}
uint8_t * b = &a[3]; //how to do this correctly when "a" is pointer?
*b = 45;
for(uint32_t i=0; i < a.size(); i++)
{ cout<<a[i]<<endl; //how to do this correctly when "a" is pointer?
}
return 0;
}
Upvotes: 1
Views: 734
Reputation: 1136
With the following declaration:
basicVector *a = new basicVector(10);
You could dereference the pointer (preferred):
uint8_t n = (*a)[5];
Or call the operator using the operator
syntax:
uint8_t n = a->operator[](5);
Upvotes: 2