创建类索引操作符[]允许字符串参数(字符串索引) [英] Creating a class indexer operator[] allowing string parameter (string index)

查看:205
本文介绍了创建类索引操作符[]允许字符串参数(字符串索引)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在c ++中创建一个类。此类必须使用集合进行管理。
确定,没问题,我想使用operator []当然,但在这种情况下,我的愿望是不通过位置索引,而是通过名称==>这意味着使用字符串索引器。

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

似乎这样的东西对我的编译器来说不太好:

It seems that something of this kind is not so nice to 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"];

编译器告诉我,他不能解决这个问题,因为operator [const char [5]]不存在。
OK OK
我可以这个...
编译器认为通过调用m [Name]我试图调用一个运算符承认一个char *,而不是一个字符串。 。ok
让我们改变代码with operator []允许一个char *作为参数...没有。

Compiler tells me that he cannot solve this because operator[const char[5]] does not exists. OK OK I could figure this... Compiler thinks that by calling m["Name"] I'm trying to call an operator admitting a char* and not a string... ok Let's change the code with operator[] allowing a char* as parameter... nothing.

有人可以告诉我如何实现这样的结果在c ++中以最佳实践方式?我想这是一个常见的问题,通过字符串索引而不是整数...
谢谢。

Can somebody tell me how to achieve such a result in c++ in a best practice way? I suppose that is a common problem to index by string and not by integer... Thank you.

推荐答案

它应该工作正常。请看这个例子,它为我编译和工作正常:

It should work fine. See this example which compiles and works ok for me:

#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 * ,因此转换应该是自动的。

And I see no reason it should not, since std::string has implicit constructor taking const char* so the conversion should be automatic.

编辑:你的主要beeing像这样:

From the comment it seems your problem was with your main beeing like this:

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

原因:

一个对象的初始化器是一个空的圆括号,即(),应该被初始化。

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

()不被初始化语法允许,

[ Note: since () is not permitted by the syntax for initializer,

X a();

一个类X的对象,但是一个函数声明没有参数并返回一个X。

is not the declaration of an object of class X, but the declaration of a function taking no argument and returning an X.

在某些其他初始化上下文中允许使用form()。 4,5.2.3,12.6.2)。 - end note]

The form () is permitted in certain other initialization contexts (5.3.4, 5.2.3, 12.6.2). — end note ]

这篇关于创建类索引操作符[]允许字符串参数(字符串索引)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆