Is it possible to call operator[] with out using * when I have a pointer to the class ?
class MyClass
{
public:
void operator[](int n)
{
cout<<"In []";
}
};
int main()
{
MyClass *a=new MyClass;
(*a)[2];//work
a[2];//It just do some pointer arithmetic ...too bad :((
}
Yes, you should be able to use the ->
operator, like this:
a->operator[] (2);
Demo on ideone.
If all you need is eliminating the asterisk, this should do the trick. If you are aiming for a better readability, this isn't of much help - you need to either avoid the pointer, or to use a regular member function:
class MyClass
{
public:
void operator[](int n)
{
cout<<"In []";
}
// Add a regular function for use with pointers
// that forwards the call to the operator[]
void at(int n) { (*this)[n]; }
};
Now you can write a->at(2);
(Demo on ideone).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With