Creating a class indexer [] operator that allows a string parameter (row index)

I want to create a class in C ++. This class must manage the collection. OK, no problem, I would like to use the [] operator, of course, but in this case my desire is not to index by position, but by name ==>, this means using a row indexer.

Something like this seems not so good for my compiler:

// In hpp
class myclass {
   ...
   ...
   std::string operator[](const std::string& name);
}
// In cpp
std::string myclass::operator[](const std::string& name) {
   ...
}
// In main
myclass m;
std::string value = m["Name"];

The compiler tells me that it cannot solve this because the [const char [5]] operator does not exist. alright alright I could understand this ... The compiler thinks that by calling m ["Name"], I am trying to call an operator that allows char * rather than a string ... ok Let me change the code using the [] operator, allowing char * as a parameter ... nothing.

- , ++ ? , , ... .

+3
2

. . , :

#include <iostream>
#include <string>

class MyClass
{
    public:
        std::string operator[] (const std::string& key) { std::cout << key << std::endl; return key; }
};

int main()
{
    MyClass obj;
    std::string s = obj["50"];
    std::cout << s << std::endl;
}

, , std::string , const char*, .

: , :

int main()
{
    MyClass obj();
    std::string s = obj["50"];
    std::cout << s << std::endl;
}

:

, , ..(), .

[: () ,

X a();

X, X.

() (5.3.4, 5.2.3, 12.6.2). - ]

+1

, , ( , operator - public, class ;). , - .

std::map<std::string, std::string> .

#include <string>
#include <map>
#include <assert.h>

int main()
{
    std::map<std::string, std::string> m;
    m["Foo"] = "Bar";
    m["Fez"] = "Baz";

    assert(m["Foo"] == "Bar");
    assert(m["Fez"] == "Baz");
}
+2

Source: https://habr.com/ru/post/1777232/


All Articles