Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

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
", 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...

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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];}
};

This allows you to modify a non-const object using the array operator.

Heap h1;
h1[0] = 10;

while still allowing you to access const objects.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...