【发布时间】:2012-12-08 09:23:23
【问题描述】:
我有这门课:
class MyClass {
public:
int operator[](const std::string&);
const std::string& operator[](const int&) const;
...
};
但是,如果我用 const 字面量 0 调用第二个运算符:
MyClass myclass;
std::cout << myclass[0] << std::endl;
我收到了这个错误:
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
我想我理解是什么情况(0 可以是字符串或整数?),但我的问题是:有没有办法解决这个问题并保持运算符重载?
【问题讨论】:
-
为什么要打扰
const int&?只需发送int。 -
string版本匹配,因为 const 文字零可以隐式转换为空const char*指针,然后从那里转换为std::string。仍在考虑如何避免这种情况。 -
我很惊讶这些被视为同等排名的转化。
-
返回
const int很奇怪(而且毫无意义)。 -
@sftrabbit:这是因为实例上的
const资格。没有它会是一个更好的过载。
标签: c++ operators operator-overloading