2

ベクトルポインタ要素にアクセスする必要があります。アニメーション構造用に次のコードがあります(ここでは簡略化されており、不要な変数は切り捨てられています)。

struct framestruct {
    int w,h;
};
struct animstruct {
    vector<framestruct> *frames;
};

vector<framestruct> some_animation; // this will be initialized with some frames data elsewhere.

animstruct test; // in this struct we save the pointer to those frames.

void init_anim(){
    test.frames = (vector<framestruct> *)&some_animation; // take pointer.
}

void test_anim(){
    test.frames[0].w; // error C2039: 'w' : is not a member of 'std::vector<_Ty>'
}

アレイは機能します。テストしました test.frames->size()。計画どおり7でした。

では、ベクトルからN番目のインデックスにあるベクトル要素(wとh)にアクセスするにはどうすればよいですか?

4

2 に答える 2

5

配列にアクセスする前に、ポインタを派生させる必要があります。->サイズを取得するためにオペレーターで行っているのと同じように。

(*test.frames)[0].w;

演算子を使用して演算子メソッドに->アクセスすることもできます[]が、構文はそれほど良くありません。

test.frames->operator[](0).w;

[]構文的に真のベクトルのように直接使用できるようにしたい場合は、framesメンバーにのコピーを許可するかvector、を参照することができますvector。または、それ自体をオーバーロード[]して、変数の構文を使用することもできます。animstruct[]test

コピー:

struct animstruct { vector<framestruct> frames; };
animstruct test;
void init_anim(){ test.frames = some_animation; }

test.frames[0].w;

参照:

struct animstruct { vector<framestruct> &frames;
                    animstruct (vector<framestruct> &f) : frames(f) {} };
animstruct test(some_animation);
void init_anim(){}

test.frames[0].w;

過負荷:

struct animstruct { vector<framestruct> *frames;
                    framestruct & operator[] (int i) { return (*frames)[i]; } };
animstruct test;
void init_anim(){ test.frames = &some_animation; }

test[0].w;
于 2012-07-20T22:04:45.530 に答える
1

test.framesベクトルを指しているため、ベクトルにインデックスを付ける前に逆参照する必要があります。

(*test.frames)[0].w
于 2012-07-20T22:05:48.363 に答える