Kush wrote:
Hello All,
Once again another question. :)
This time I would like to understand why one needs to overload the [ ]
operator to access objects in array format?
Example code:
class A {
{ };
class B {
private:
A array[10];
A* pA = array;
public:
A& operator [ ] (int i) { return pA[i]; } //Line 1:
void do_something(void) {
A a;
a = pA[2]; } //Line 2
};
Why do I need Line 1? Since pA is a pointer of type A, can I not
directly access "array members" using simple pointer arithmetic?
Line 1 is there to access the array from the outside world. You don't
need the pointer pA at all.
array already decays to a pointer anyways.
>
i.e. without declaring Line 1, use Line 2
or equivalently use the below statement to replace Line 2
a = *(pA + 2);
There is no need:
A a = array[2];
will do
Try something like this, although a std::vector would be more usefull:
#include <iostream>
#include <stdexcept>
class A { };
template< typename T , const size_t Size >
class B
{
T array[Size];
public:
A& operator [ ] (size_t i)
{
if(i < 0 || i Size - 1)
throw std::out_of_range("array out of bounds");
return array[i];
}
void do_something()
{
T a;
a = array[2];
}
};
int main()
{
try {
B< A, 10 b;
// A a = b[11]; // throws
b.do_something();
}
catch( const std::exception& r_e )
{
std::cerr << "Error: ";
std::cerr << r_e.what() << std::endl;
}
}
___
Note that a std::vector has an at(...) member function that does the
range_check for you.
Its so much easier to do the above with a vector.
#include <iostream>
#include <vector>
#include <stdexcept>
template< typename T >
class B
{
std::vector< T vt;
public:
B(size_t size, const T& t = T())
: vt(size, t) { } // ctor
T& operator[](size_t i)
{
return vt.at(i);
}
void do_something()
{
vt.at(2) = 33.3;
}
};
int main()
{
try {
B< double b( 5, 11.1 );
// A a = b[11]; // throws
b.do_something();
for(size_t i = 0; i < 10; ++i)
{
std::cout << "b[" << i << "] = ";
std::cout << b[i] << std::endl;
}
}
catch( const std::exception& r_e )
{
std::cerr << "Error: ";
std::cerr << r_e.what() << std::endl;
}
}
/*
b[0] = 11.1
b[1] = 11.1
b[2] = 33.3
b[3] = 11.1
b[4] = 11.1
*/