0

I have a class that holds an array of integers and to get a reference of this array the subscript operator [] is overloaded (this is a stripped down example with logic checks etc removed):

class Foo {
public:

Foo() {};

// and overload the [] operator
int& operator[](const int index);

private:
const int LEN = 7;
int arr[LEN];
};

int& Foo::operator[](const int index) {
    return arr[index];
}

A pointer of an instance of such class (named boo) is passed to a function. Now what I want to do is:

int val = boo[0];

but it fails "error: invalid cast from type ‘Foo’ to type ‘int’".

My first idea was that Im passing a pointer to a class and I should bring a copy of the instance into scope and use that copy instead. This works. But Im curious if it would be possible to use the user defined type as a true built in type? Should I use a wrapper?

4

2 に答える 2

3

オーバーロードされた演算子は、オブジェクトへのポインターではなく、オブジェクトに対して定義されているためです。2つのオプションがあります。

int val = boo->operator[](0);

また

int val = (*boo)[0];

または、オブジェクトへのポインタの代わりに、オブジェクトを(値または参照で)渡すことができます。

あなたのケースは以下と同等です:

Boo* b = ....;
b[0];           //this returns a Boo object

とは対照的に:

Boo b;
b[0];           //calls operator[]
于 2012-10-29T12:08:36.387 に答える
3

次のいずれかを使用する必要があります:

boo->operator[] ( 0 );

また

(*boo)[0];

IEは、オブジェクトbooへのポインターを間接参照します。

于 2012-10-29T12:08:58.693 に答える