相关疑难解决方法(0)

"运算符[]'的模糊重载"如果存在转换运算符到int

我正在尝试像类的[]运算符一样实现矢量和地图.但我收到编译器的错误消息(g ++和clang ++).发现只有当类还将转换运算符转换为整数类型时才会出现它们.

现在我有两个问题.首先是我不知道为什么编译器无法区分[](const std :: string&)以及类何时将转换运算符转换为int.第二个......我需要转换和索引运算符.有谁知道如何解决这个问题?

在此先感谢并向我致以最诚挚的问候

作品:

#include <stdint.h>
#include <string>

struct Foo
{
    Foo& operator[](const std::string &foo) {}
    Foo& operator[](size_t index) {}
};

int main()
{
    Foo f;
    f["foo"];
    f[2];
}
Run Code Online (Sandbox Code Playgroud)

不起作用:

#include <stdint.h>
#include <string>

struct Foo
{
    operator uint32_t() {}
    Foo& operator[](const std::string &foo) {}
    Foo& operator[](size_t index) {}
};

int main()
{
    Foo f;
    f["foo"];
    f[2];
}
Run Code Online (Sandbox Code Playgroud)

编译器错误:

main.cpp: In function 'int main()':
main.cpp:14:9: error: ambiguous overload for 'operator[]' in 'f["foo"]'
main.cpp:14:9: note: candidates …
Run Code Online (Sandbox Code Playgroud)

c++

14
推荐指数
1
解决办法
2752
查看次数

标签 统计

c++ ×1