C ++重载数组运算符

时间:2016-05-05 05:30:21

标签: c++ arrays operator-overloading heap

我正在创建一个堆,就像这样:

struct Heap{
    int H[100];
    int operator [] (int i){return H[i];}
    //...    
};

当我尝试从中打印元素时,我喜欢这样:

Heap h;
//add some elements...
printf("%d\n", h[3]); //instead of h.H[3]

我的问题是,如果不是访问我想设置它们,就像这样:

for(int i = 0; i < 10; i++) h[i] = i;

我该怎么办?我不能这样做,我做了......

谢谢!

3 个答案:

答案 0 :(得分:16)

提供operator[]函数的一些重载是惯用的 - 一个用于const个对象,一个用于非const个对象。 const成员函数的返回类型可以是const&,也可以只是一个值,具体取决于返回的对象,而非const成员函数的返回类型通常是引用。

struct Heap{
    int H[100];
    int operator [] (int i) const {return H[i];}
    int& operator [] (int i) {return H[i];}
};

这允许您使用数组运算符修改非const对象。

Heap h1;
h1[0] = 10;

虽然仍允许您访问const个对象。

Heap const h2 = h1;
int val = h2[0];

答案 1 :(得分:5)

您可以返回对应该设置的内容的引用。将&添加到返回类型。

int& operator [] (int i){return H[i];}

答案 2 :(得分:3)

您应该通过引用返回。使用当前版本,您将复制并编辑此副本,这不会影响原始阵列。您必须将运算符重载更改为:

int& operator [] (int i){return H[i];}