此代码编译并运行公共隐式bool强制转换(在下面注释,在http://ideone.com/FDJHB)或通过公共隐式int强制转换,后跟隐式int转换为bool强制转换(如下所示,{{3 }})。但是,将bool强制转换为私有(在http://ideone.com/kHQ46下面注释掉)会导致编译错误。在这种情况下,为什么通过int的路由不再是一个选项?像这样的连续演员是否定义了行为?感谢。
#include <iostream>
class MyObject {
public:
MyObject(int theInt) : theInt_(theInt) {
return;
}
MyObject& operator=(MyObject& source) {
std::cout << "assign op" << std::endl;
theInt_ = source.theInt_;
return *this;
}
friend MyObject operator*(MyObject& lhs, MyObject& rhs);
operator int() {
std::cout << "int conv" << std::endl;
return theInt_;
}
/*
operator bool() {
std::cout << "bool conv" << std::endl;
return theInt_;
}
*/
private:
int theInt_;
MyObject(MyObject& source);
// operator bool();
};
MyObject operator*(MyObject& lhs, MyObject& rhs) {
std::cout << "mult op" << std::endl;
return MyObject(lhs.theInt_*rhs.theInt_);
}
int main(int argc, char* argv[]) {
MyObject a(1);
MyObject b(2);
MyObject c(3);
if (a * b = c) std::cout << "Oh-no!" << std::endl;
return 0;
}
编辑:根据要求,提供相关的编译器消息。
1)输出代码给定,转换为int到bool:
mult op
int conv
分配op
int conv
喔-没有!
2)使用public bool cast输出代码:
mult op
int conv
分配op
bool conv
喔-没有!
3)如果bool强制转换为私有的编译器错误:
prog.cpp: In function ‘int main(int, char**)’:
prog.cpp:34: error: ‘MyObject::operator bool()’ is private
prog.cpp:50: error: within this context
答案 0 :(得分:5)
为了将您的类型转换为bool
,编译器会根据(相当复杂的)规则集选择“最佳”转换路径。
如果定义了operator bool()
,则提供的转化效果优于operator int()
,然后从int
转换为bool
;转化次数较少的路径被视为“更好”。
在此过程中不会考虑辅助功能,因此即使它是私有的,它也会选择operator bool()
。然后编译将失败,因为operator bool()
是私有的。
答案 1 :(得分:2)
简而言之,编译器选择首先调用哪个方法,然后检查它是否允许执行它。如果它operator bool
可以看到if
检查的最佳匹配,那么它会选择那个,然后发现它是私有的,无法使用
另请注意,(a * b = c)
将c
分配给乘法返回的临时值,然后评估该值是零还是非零。我无法想到这样的事情会有用的场景。