jeudi 1 juin 2017

Overloading operator[] taking non-integer values

I want to use the following class:

class A {
public:
     A() { /* do something */ }
     int& operator[](int index) { return data[i]; }
     int& operator[](std::string text) { return data[textToIndex(text)]; }
private:
     int textToIndex(std::string text) { /* select the right index for the given text */ }
     int data[4];
};

Can I do that? Searching online, I found that it is allowed to overload the subscript operator in this way and actually I don't get any compile error, but whenever I try to use this I get the message:

 array subscript is not an integer

I'm using c++11 on Eclipse Neon, compiling with the following string:

 g++ -std=c++0x -O0 -g3 -Wall -c -fmessage-length=0

Aucun commentaire:

Enregistrer un commentaire