I have class A and B.
Class A has some fields.
Class B is like:
class B {
public:
A* operator[]( int id ) {
return m_field.at( id );
}
/* also tried this one, but there are the same errors
A*& operator[]( int id ) {
return m_field.at( id );
}
*/
private:
vector<A*> m_field;
};
why am I getting errors while executing:
B* B_instance = new B();
B_instance[some_int]->some_field_from_A;
the errors are:
error C2819: type ‘B’ does not have an overloaded member ‘operator ->’
error C2039: ‘some_field_from_A’ : is not a member of ‘B’
an why do I need to have -> operator overloading and how it should looks like? It doesn’t make sense to me.
I am using Visual Studio 2012.
The indexing operator applies to something of type
B, not of typeB *. Therefore, to use the indexing operator, you need to first dereference your pointer (or not use one at all):The reason for the error is because pointers can be indexed, as they are capable of representing an array, as in the example below:
So when you index a
B *, it gives you back aBthat’s most likely out of bounds of your imaginary array. Then, you use the arrow operator on thatBobject when it expects a dot operator instead. Either way if you use pointers, dereference it, then index it, then use the arrow.