gpt4 book ai didi

c++ - 使用 operator[] 和 operator int() 的模糊重载

转载 作者:行者123 更新时间:2023-11-30 02:14:01 31 4
gpt4 key购买 nike

我正在创建一个类 Item,每个 Item 都是一个键/值对。此外,每个项目还可能包含子项目:

#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;
}

当我尝试编译它时,我得到:

错误:“operator[]”的不明确重载(操作数类型为“Item”和“const char [4]”)

如果我创建一个成员方法 unsigned int Get() 而不是 operator int() 它会编译。但我希望类的工作方式与 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;
}

我怎样才能让它工作?谢谢!

最佳答案

问题是您与内置的 operator[](unsigned int, const char *) 发生冲突(是的,这是一回事)。

在应用运算符之前,将操作数隐式转换为std::string或将Item隐式转换为unsigned int [] 对于编译器来说是等价的,所以它不能在两者之间进行选择。

您可以通过向类的 operator[] 添加显式 const char* 重载来解决此问题,该重载遵循您的 std::string 实现。

// Search or Create new SubItem.
Item& operator[]( const char* key ) {
return (*this)[std::string(key)];
}

关于c++ - 使用 operator[] 和 operator int() 的模糊重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58595624/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com