1

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 the ptr[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 achieve.
Else I need fix it by royal method of changing every line of code :) .

4

2 に答える 2

3

はい、すべての引数が組み込み型であるカスタム演算子を定義することはできません (これには生のポインターが含まれます)。

また、このような明白でない方法で演算子を定義することは、ほとんどの場合良い考えではありません。

X生のポインターを、そのように動作するクラスと交換することを検討することをお勧めします。コードによっては、この方が簡単な場合があります (たとえば、多数のテンプレートがある場合)。

于 2010-05-24T14:18:51.790 に答える
2

Alexが言うように、あなたの「サブインデックス」の使用法は、[]あなたのコードを読んでいる人にとってはまったく自明ではありません。

そうは言っても、次のようなクラスを定義できます。

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]]; }
};

X *ptr = new X[10];そして、をに置き換えますSubindexingList<X> stuff(10);

于 2010-05-24T14:29:59.603 に答える