【发布时间】:2010-11-27 21:48:23
【问题描述】:
我想用 C++ 创建一个类。此类必须使用集合进行管理。 好的,没问题,我当然想使用 operator[] 但是,在这种情况下,我希望不按位置索引,而是按名称索引 ==> 这意味着使用字符串索引器。
似乎这种东西对我的编译器来说不是很好:
// 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]] 不存在。 好的好的 我能想到这个... 编译器认为通过调用 m["Name"] 我试图调用一个承认 char* 而不是字符串的操作员......好的 让我们用 operator[] 更改代码,允许 char* 作为参数......什么都没有。
有人可以告诉我如何以最佳实践方式在 c++ 中实现这样的结果吗?我想这是按字符串而不是整数索引的常见问题... 谢谢。
【问题讨论】:
-
当你尝试
std::string value = m[std::string("Name")];时会发生什么 -
我很确定编译器是一个she
-
@TokenMacGuy,std::string 有一个接受 char* 的 ctor,所以没关系。
标签: c++ string indexing operator-overloading