【发布时间】:2018-02-05 15:25:41
【问题描述】:
operator bool 在以下示例中打破了operator< 的使用。谁能解释为什么bool 在if (a < 0) 表达式中与特定运算符一样相关,是否有解决方法?
struct Foo {
Foo() {}
Foo(int x) {}
operator bool() const { return false; }
friend bool operator<(const Foo& a, const Foo& b) {
return true;
}
};
int main() {
Foo a, b;
if (a < 0) {
a = 0;
}
return 1;
}
当我编译时,我得到:
g++ foo.cpp
foo.cpp: In function 'int main()':
foo.cpp:18:11: error: ambiguous overload for 'operator<' (operand types are 'Foo' and 'int')
if (a < 0) {
^
foo.cpp:18:11: note: candidate: operator<(int, int) <built-in>
foo.cpp:8:17: note: candidate: bool operator<(const Foo&, const Foo&)
friend bool operator<(const Foo& a, const Foo& b)
【问题讨论】:
-
0是int类型,而不是Foo类型 -
你真的需要这两种隐式转换吗?单一的隐式转换可能会让人头疼,但两种方式的隐式转换肯定会引发偏头痛。
-
制作单参数构造函数
explicit -
顺便说一句:您还没有为
a = 0;定义赋值运算符,这可能会导致另一个错误消息... -
这是问题的简化示例。
标签: c++ type-conversion operators ambiguous