数组运算符重载

Array operator overloading

本文关键字:重载 运算符 数组      更新时间:2023-10-16

我有A类和B类。

A类有一些字段。B类类似于:

class B {
public:
    A* operator[]( int id ) {
        return m_field.at( id );
    }
    /* also tried this one, but there are the same errors
    A*& operator[]( int id ) {
        return m_field.at( id );
    }
    */
private:
    vector<A*> m_field;
};

为什么我在执行时出错:

B* B_instance = new B();
B_instance[some_int]->some_field_from_A;

错误是:

错误C2819:类型"B"没有重载的成员"operator->">

错误C2039:"some_field_from_A":不是"B"的成员

a为什么我需要->运算符重载以及它应该是什么样子?这对我来说没有意义。

我正在使用Visual Studio 2012。

索引运算符应用于B类型的对象,而不是B *类型的对象。因此,要使用索引运算符,您需要首先取消引用指针(或者根本不使用指针(:

(*B_instance)[some_int]...

错误的原因是指针可以被索引,因为它们能够表示数组,如下例所示:

int arr[2] = {0, 1};
int *p = arr; //array to pointer conversion
p[1] = 2; // now arr is {0, 2}

因此,当你索引一个B *时,它会返回一个很可能超出想象数组边界的B。然后,当B对象需要点运算符时,可以在该对象上使用箭头运算符。无论哪种方式,如果使用指针,请先取消引用,然后索引,然后使用箭头。