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屋!