给定以下代码:
#include <string>
#include <sstream>
class SomeClass {
public:
SomeClass& operator<<(long value) { return *this; }
SomeClass& operator<<(unsigned long value) { return *this; }
SomeClass& operator<<(float value) { return *this; }
SomeClass& operator<<(double value) { return *this; }
SomeClass& operator<<(long double value) { return *this; }
SomeClass& operator<<(bool value);
{ return *this; }
SomeClass& operator<<(const void* value);
{ return *this; }
SomeClass& operator<<(::std::string aString) { return *this; }
};
int main() {
SomeClass aClass;
std::ostringstream aStream;
aClass << 2;
aClass << "Hello World";
aClass << '\0';
aClass << -2;
aStream << 2;
aStream << "Hello World";
aStream << '\0';
aStream << -2;
return 0;
}
为什么是basic_ostream
能够重载<<
这么多整数类型没问题?然而,编译器为 SomeClass 的 << 运算符提供了不明确的重载错误?
例如:
../OverloadTest.cpp:65: error: ambiguous overload for ‘operator<<’ in ‘aClass << 2’
../OverloadTest.cpp:14: note: candidates are: SomeClass& SomeClass::operator<<(long int)
../OverloadTest.cpp:19: note: SomeClass& SomeClass::operator<<(long unsigned int)
../OverloadTest.cpp:24: note: SomeClass& SomeClass::operator<<(float)
../OverloadTest.cpp:29: note: SomeClass& SomeClass::operator<<(double)
../OverloadTest.cpp:35: note: SomeClass& SomeClass::operator<<(long double)
../OverloadTest.cpp:40: note: SomeClass& SomeClass::operator<<(bool)
../OverloadTest.cpp:46: note: SomeClass& SomeClass::operator<<(const void*)
../OverloadTest.cpp:51: note: SomeClass& SomeClass::operator<<(std::string)
最佳答案
您至少需要为 int
添加重载(以及完成 unsigned int
的代码)。
SomeClass& operator<<(int value) { return *this; }
SomeClass& operator<<(unsigned int value) { return *this; }
当您调用时:aClass << 2;
文字 2
类型为 int
, 并没有重载完全吻合,编译器需要对数字进行转换,在转换中就是出现歧义的地方。 2
用什么比较好, long
或 unsigned long
或 float
或 double
或 long double
甚至 bool
,编译器不知道。
关于c++ - 在 C++ 中重载运算符时如何防止整数歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25552808/