但是,另一个模棱两可的重载运算符!尽管存在许多此类问题,但我遇到了clang++-6.0
给出的另一个问题,使它们无法解决。一个类型转换运算符定义使[]
重载以给出错误。对我来说没有任何意义。
#include <string>
#include <iostream>
using namespace std;
struct Obj_ {
Obj_& operator [] (const char*) {
cout << "const char* subscript." << endl;
return *this;
}
Obj_& operator [] (const string&) {
cout << "const string& subscript." << endl;
return *this;
}
operator int () {
cout << "int cast." << endl;
return 0;
}
};
int main () {
Obj_ Obj;
char Str1[5] = "test";
string Str2 = "test";
Obj[Str1];
Obj[Str2][Str1];
return 0;
}
编译后吐出
/tests/test_ambiguity.cpp:26:7: error:
use of overloaded operator '[]' is ambiguous (with operand types 'Obj_'
and 'char [5]')
Obj[Str1];
~~~^~~~~
/tests/test_ambiguity.cpp:7:11: note:
candidate function
Obj_& operator [] (const char*) {
^
/tests/test_ambiguity.cpp:11:11: note:
candidate function
Obj_& operator [] (const string&) {
^
/tests/test_ambiguity.cpp:26:7: note:
built-in candidate operator[](int, char *)
Obj[Str1];
^
/tests/test_ambiguity.cpp:26:7: note:
built-in candidate operator[](int, const char *)
/tests/test_ambiguity.cpp:26:7: note:
built-in candidate operator[](int, volatile char *)
/tests/test_ambiguity.cpp:26:7: note:
built-in candidate operator[](int, const volatile char *)
/tests/test_ambiguity.cpp:27:13: error:
use of overloaded operator '[]' is ambiguous (with operand types 'Obj_'
and 'char [5]')
Obj[Str2][Str1];
~~~~~~~~~^~~~~
/tests/test_ambiguity.cpp:7:11: note:
candidate function
Obj_& operator [] (const char*) {
^
/tests/test_ambiguity.cpp:11:11: note:
candidate function
Obj_& operator [] (const string&) {
^
/tests/test_ambiguity.cpp:27:13: note:
built-in candidate operator[](int, char *)
Obj[Str2][Str1];
^
/tests/test_ambiguity.cpp:27:13: note:
built-in candidate operator[](int, const char *)
/tests/test_ambiguity.cpp:27:13: note:
built-in candidate operator[](int, volatile char *)
/tests/test_ambiguity.cpp:27:13: note:
built-in candidate operator[](int, const volatile char *)
2 errors generated.
CMakeFiles/test_ambiguity.dir/build.make:62: recipe for target 'CMakeFiles/test_ambiguity.dir/tests/test_ambiguity.cpp.o' failed
make[2]: *** [CMakeFiles/test_ambiguity.dir/tests/test_ambiguity.cpp.o] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/test_ambiguity.dir/all' failed
make[1]: *** [CMakeFiles/test_ambiguity.dir/all] Error 2
Makefile:140: recipe for target 'all' failed
make: *** [all] Error 2
gcc
编译得很好,而clang
编译得不好。即使没有使用类型转换运算符,也没有错误!