解决运算符[]的模糊重载

Won*_*abo 6 c++ operator-overloading operators

我有这门课:

class MyClass {

    public:

        int operator[](const std::string&);
        const std::string& operator[](const int&) const;

    ...
};
Run Code Online (Sandbox Code Playgroud)

但是,如果我调用第二个运算符w/const literal 0,它的工作量很大:

MyClass myclass;
std::cout << myclass[0] << std::endl;
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误:

In function 'int main()':
ambiguous overload for 'operator[]' in 'myclass[0]'
note: candidates are:
note: const int MyClass::operator[](const string&)|
note: const string& MyClass::operator[](const int&) const
Run Code Online (Sandbox Code Playgroud)

我想我明白了什么情况(0可以是字符串或int?),但我的问题是:有没有办法解决这个问题并保持运算符重载?

asc*_*ler 6

通话MyClass::operator[](const std::string&)涉及转换:

myclassMyClass&MyClass&:完美匹配

0intconst char*std::string:用户定义的转换

通话MyClass::operator[](const int&) const涉及转换:

myclass从:MyClass&const MyClass&const资格

0intint:完美匹配

在这种情况下,当一个重载对于参数X"更好"但是对于参数Y不同的重载是"更好"时,过载都不能被认为是最好的重载,并且编译器必须抱怨(假设没有第三次重载超过两者) .

是否可以将两个重载更改为两者const或两者non-const?如果没有,您可以添加第三个重载来处理这种情况:

const std::string& operator[](int n) {
    return static_cast<const MyClass&>(*this)[n];
}
Run Code Online (Sandbox Code Playgroud)