C++ 重载数组运算符 [英] C++ overloading array operator
问题描述
我正在创建一个堆,如下所示:
I'm creating a Heap, like this:
struct Heap{
int H[100];
int operator [] (int i){return H[i];}
//...
};
当我尝试从中打印元素时,我喜欢这样:
When I try to print elements from it I do like this:
Heap h;
//add some elements...
printf("%d\n", h[3]); //instead of h.H[3]
我的问题是,如果不是访问我想设置它们,像这样:
My question is, if instead of accessing I want to set them, like this:
for(int i = 0; i < 10; i++) h[i] = i;
我该怎么办?我不能就那样做...
How can I do? I can't just do this way i did...
谢谢!
推荐答案
提供 operator[]
函数的几个重载是惯用的 - 一个用于 const
对象一个用于非const
对象.const
成员函数的返回类型可以是 const&
或只是一个值,这取决于返回的对象,而非const
成员函数通常是一个引用.
It is idiomatic to provide couple of overloads of the operator[]
function - one for const
objects and one for non-const
objects. The return type of the const
member function can be a const&
or just a value depending on the object being returned while the return type of the non-const
member function is usually a reference.
struct Heap{
int H[100];
int operator [] (int i) const {return H[i];}
int& operator [] (int i) {return H[i];}
};
这允许您使用数组运算符修改非const
对象.
This allows you to modify a non-const
object using the array operator.
Heap h1;
h1[0] = 10;
同时仍然允许您访问 const
对象.
while still allowing you to access const
objects.
Heap const h2 = h1;
int val = h2[0];
这篇关于C++ 重载数组运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!