我已经实现了以下包装共享指针的类。
class Wrapper
{
private:
std::shared_ptr<const MyClass> mPointer;
public:
Wrapper(MyClass* myClass);
operator bool(void) const;
const MyClass* operator*(void) const;
const MyClass* operator->(void) const;
Wrapper operator!(void) const;
Wrapper operator||(Wrapper rhs) const;
Wrapper operator&&(Wrapper rhs) const;
};
类Wrapper本身的对象应该像一个布尔值,可以写:
Wrapper Wrapper_A = Wrapper(new MyClass(true));
Wrapper Wrapper_B = Wrapper(new MyClass(false));
if(Wrapper_A && Wrapper_B) {}
现在,请考虑以下功能:
void WrapperHandler::add(Wrapper wrapper);
如果以下列方式使用此功能:
add(Wrapper_A);
或
add(!Wrapper_A);
没有问题发生。
但是当我写作
add(Wrapper_A || Wrapper_B);
发生以下编译错误(VS 2010):
Error 1 error C2664: 'WrapperHandler::add' : cannot convert parameter 1 from 'bool' to 'Wrapper'
如果我重载运算符||按以下方式(隐藏内置运算符):
Wrapper operator||(const Wrapper& rhs) const;
然而,错误发生了。
以下几行正常运作:
bool test = Wrapper_A || Wrapper_B;
为什么运算符||的结果总是投奔布尔?
非常感谢提前
答案 0 :(得分:4)
为什么运算符
||
的结果总是强制转换为bool?
根据规范(http://en.cppreference.com/w/cpp/language/operators),它不是:
除了上面的限制之外,语言对重载运算符的作用或返回类型没有其他限制
这是运营商优先权不符合您预期的情况。
你有这个被覆盖的运营商:
operator bool(void) const;
这意味着,如果可能,编译器会尝试将您的对象转换为bool
。当编译器遇到这个时:
add(Wrapper_A || Wrapper_B);
它正在将Wrapper_A
和Wrapper_B
转换为bool
,然后然后将||
运算符转换为转换结果。< / p>
要解决此问题,请确保将bool
运算符标记为explicit
,这将阻止此转换自动发生。
explicit operator bool(void) const;