【问题标题】:Ambiguous overloading with operator[] and operator int()使用 operator[] 和 operator int() 进行模棱两可的重载
【发布时间】:2020-02-23 23:54:50
【问题描述】:

我正在创建一个类 Item,每个 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;
}

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

【问题讨论】:

标签: c++ c++11 overloading


【解决方案1】:

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

在应用operator[]之前将操作数隐式转换为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)];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-08
    • 2012-07-14
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多