我试图实现向量like和像[]运算符类的映射。但是我收到了编译器(g ++和clang ++)的错误消息。发现只有当类也有转换运算符为整数类型时才会发生。“运算符[]'”的模糊过载如果转换运算符到int存在
现在我有两个问题。首先是我不知道为什么编译器无法区分[](const std :: string &)和何时该类有转换运算符来输入。 第二...我需要转换和索引运算符。有谁知道如何解决这个问题?
在此先感谢和我最诚挚的问候
作品:
#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];
}
不起作用:
#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];
}
编译器错误:
main.cpp: In function 'int main()':
main.cpp:14:9: error: ambiguous overload for 'operator[]' in 'f["foo"]'
main.cpp:14:9: note: candidates are:
main.cpp:14:9: note: operator[](long int, const char*) <built-in>
main.cpp:7:7: note: Foo& Foo::operator[](const string&)
main.cpp:8:7: note: Foo& Foo::operator[](size_t) <near match>
main.cpp:8:7: note: no known conversion for argument 1 from 'const char [4]' to 'size_t {aka long unsigned int}'
有没有这样的事情作为“演员操作员”。有问题的运营商是**转换**。强制转换是您在源代码中编写的内容,以告知编译器进行转换。 – 2013-04-06 18:46:00
谢谢@Pete Becker指出这一点。 – r2p2 2013-04-06 18:57:59