How to change the meaning of pointer access operator
This may be very obvious question, pardon me if so.
I have below code snippet out of my project,
#include <stdio.h>
class X
{
public:
int i;
X() : i(0) {};
};
int main(int argc,char *arv[])
{
X *ptr = new X[10];
unsigned index = 5;
cout<<ptr[index].i<<endl;
return 0;
}
Question
Can I change the meaning of theptr[index]
? Because I need to return the value of ptr[a[index]]
where a is an array for subindexing. I do not want to modify existing source code. Any new function added which can change the behavior is needed.
Since the access to index operator is in too many places (536 to be precise) in my code, and has complex formulas inside the index subscript operator, I am not inclined to change the code in many locations.
PS :
1. I tried operator overload and came to conclusion that it is not possible. 2. Also p[i] will be transformed into *(p+i). I cannot redefine the basic operator '+'.So just want to reconfirm my understanding and if there are any possible short-cuts to a开发者_Python百科chieve.
Else I need fix it by royal method of changing every line of code :) .Yes, it is not possible to define custom operators where all of the arguments are of built-in types (this includes raw pointers).
Also it's almost always not a good idea to define operators in a non-obvious way like this.
You may want to consider swapping out a raw pointer to X
with a class that behaves like one. It may be easier, depending on your code (e.g. if you have a lot of templates).
As Alex says, your 'subindexing' usage of []
would be totally nonobvious for anyone reading your code.
That said, you can define a class such as this:
template<class T>
class SubindexingList {
vector<T> data;
vector<int> subindexes;
public:
SubindexingList(int count) : data(count) { }
void set_subindexes(vector<T> const& newval) { subindexes = newval; }
T& operator[](int index) { return data[subindexes[index]]; }
T const& operator[](int index) const { return data[subindexes[index]]; }
};
And replace your X *ptr = new X[10];
with SubindexingList<X> stuff(10);
.
精彩评论