Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a pointer to a C++ object what are all the correct ways to call the operator[] function?

I am writing a time varying profile class using templates and want to index the profile by either a numeric index or by a date and time as represented by a struct tm. The indexing by a numeric index works fine, but the indexing by a date doesn't work with a pointer to the object. Here is some sample code containing approaches that work and approaches that don't work.

#include "profile.h" // Class Profile<T> is declared and defined here.
float f;
int i;
struct tm d;
Profile<float> p;
Profile<float> *pPtr;

// Non-pointer syntax
f = p[i];                // this works.
f = p.operator[](i);     // this works, but its ugly.
f = p[d];                // this works.
f = p.operator[](d);     // this works, but its ugly.

// Pointer syntax
f = (*pPtr)[i];          // this works.
f = pPtr->operator[](i); // this works, but its ugly.
f = (*pPtr)[d];          // this isn't what I typed.  I did f = *(pPtr)[d];
f = pPtr->operator[](d); // this works, but its ugly.

This C++ code is being written in Visual Studio 2008. The compiler error message is error C2677 binary '[' : no global operator found which takes type 'tm' (or there is no acceptable conversion).

Given a pointer to a C++ object what are all the correct ways to call the operator[] function?

like image 299
J Edward Ellis Avatar asked Feb 01 '26 06:02

J Edward Ellis


1 Answers

The code you've shown here is fine; probably in your previous attempts you were doing *(pPtr)[d] instead of (*pPtr)[d], which would understandably cause an error since operator* has lower precedence than operator[].

like image 142
ildjarn Avatar answered Feb 03 '26 21:02

ildjarn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!