【发布时间】:2014-03-30 15:30:55
【问题描述】:
如果下面的测试程序
#include <iostream>
class A {
public:
A() {}
explicit operator bool() const {
std::cout << __PRETTY_FUNCTION__ << std::endl;
return true;
}
// explicit operator bool() {
// std::cout << __PRETTY_FUNCTION__ << std::endl;
// return true;
// }
const operator int() const {
std::cout << __PRETTY_FUNCTION__ << std::endl;
return 1;
}
operator int() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
return 1;
}
};
int main() {
A a;
if (a) {
std::cout << "bool()" << std::endl;
}
if (a + 0) {
std::cout << "int()" << std::endl;
}
}
运行,输出为
int A::operator int()
bool()
int A::operator int()
int()
而不是
bool A::operator _Bool()
bool()
int A::operator int()
int()
我的预期(以及如果您取消注释注释部分会得到什么)。
那么问题是,转换为非 const-int 优先于转换为 const-bool 的规则是什么?
【问题讨论】:
-
哪个编译器?
const operator int() const应该编译失败 -
编译器是clang-3.4
-
您能否更新问题标题以删除双重否定。我会自己做,但我不确定是否删除“不”或“不”。或者两者兼而有之?
-
好的,刚刚清除了标题。谢谢!
标签: c++ c++11 operator-overloading