[英]Ambiguous overloading with operator[] and operator int()
I am creating a class Item, and each Item is a key/value pair.我正在创建一个 class 项目,每个项目都是一个键/值对。 Also, each Item may also contain subitems:
此外,每个项目还可能包含子项目:
#include <string>
#include <vector>
#include <iostream>
class Item
{
private:
std::string key;
unsigned int value;
std::vector<Item> subitems;
public:
Item( const std::string& key = "", const int& value = 0 )
: key( key ), value( value ){ };
public:
// Search or Create new SubItem.
Item& operator[]( const std::string& key )
{
for( auto& subitem : subitems )
if( subitem.key == key )
return subitem;
subitems.push_back( Item( key ));
return subitems.back( );
}
public:
// Assign new value to Item.
Item& operator=( const int& value )
{
this->value = value;
return *this;
}
public:
// Get value from Item.
operator unsigned int( ) const
{
return value;
}
};
int main( void )
{
Item item;
item["sub"] = 42;
unsigned int sub = item["sub"];
std::cout << std::to_string( sub ) << std::endl;
return 0;
}
When I try to compile this, I get:当我尝试编译它时,我得到:
error: ambiguous overload for 'operator[]' (operand types are 'Item' and 'const char [4]')错误:“operator[]”的重载不明确(操作数类型为“Item”和“const char [4]”)
If I create a member method unsigned int Get() instead of operator int() it does compile.如果我创建一个成员方法unsigned int Get()而不是operator int()它会编译。 But I wanted the class to work the same way that std::map works:
但我希望 class 的工作方式与 std::map 的工作方式相同:
#include <map>
#include <string>
#include <iostream>
int main( void )
{
std::map<std::string, unsigned int> item;
item["sub"] = 42;
unsigned int sub = item["sub"];
std::cout << std::to_string( sub ) << std::endl;
return 0;
}
How can I get it working?我怎样才能让它工作? Thanks!
谢谢!
The problem is that you are conflicting with the builtin operator[](unsigned int, const char *)
(yes, that's a thing).问题是您与内置
operator[](unsigned int, const char *)
冲突(是的,这是一回事)。
Implicitely converting the operand to a std::string
or implicitely converting the Item
to an unsigned int
before applying the operator[]
is equivalent for the compiler, so it can't choose between the two.在应用
operator[]
之前将操作数隐式转换为std::string
或将Item
隐式转换为unsigned int
对于编译器来说是等效的,因此它不能在两者之间进行选择。
You can work around this by adding an explicit const char*
overload to your class' operator[]
that defers to your std::string
implementation.您可以通过向您的类的
operator[]
添加显式的const char*
重载来解决此问题,该操作符遵循您的std::string
实现。
// Search or Create new SubItem.
Item& operator[]( const char* key ) {
return (*this)[std::string(key)];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.