C++ 解决模糊运算符重载问题

C++ 解决模糊运算符重载问题,c++,C++,我已经实现了下面的类,它包装了一个共享指针 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->

我已经实现了下面的类,它包装了一个共享指针

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;
};

现在,考虑以下函数:

void WrapperHandler::add(Wrapper wrapper);
如果按以下方式使用此功能:

add(Wrapper_A);

没有问题发生

但是当我写作的时候

add(Wrapper_A || Wrapper_B);
发生以下编译错误(VS 2010):

如果我以以下方式重载运算符| |(以隐藏内置运算符):

尽管如此,还是出现了错误

以下线路工作正常:

bool test = Wrapper_A || Wrapper_B;
为什么运算符| |的结果总是转换为布尔值

非常感谢

为什么运算符
|
的结果总是强制转换为布尔值

根据规范(),它不是:

除了上面的限制之外,该语言对重载运算符的操作或返回类型没有其他限制

这是一种运算符优先级不是您所期望的情况

您有此被重写的运算符:

Wrapper operator||(const Wrapper& rhs) const;
operator bool(void) const;
这意味着,如果可能,编译器将尝试将对象转换为
bool
。当编译器遇到以下情况时:

add(Wrapper_A || Wrapper_B);
它将
Wrapper_A
Wrapper_B
转换为
bool
,然后对转换结果运行
|
操作符

要解决此问题,请确保将
bool
运算符标记为
explicit
,这将自动停止此转换

explicit operator bool(void) const;

首先,您应该根据发布指南提取一个最小的示例。然后,考虑使用非成员运算符,至少对于二进制运算符。我想你问的问题是错误的。VisualStudio 2010不支持C11特性。我很惊讶你居然能使用
共享ptr
。错误消息告诉你
|
返回一个
bool
-这只能是因为你在执行两个
运算符bool)const
结果的逻辑or,因此,将该操作符显式化,您的问题就会消失。@RSahu VS 2010实际上支持很多C++11功能。到目前为止,不是所有的,而是一个重要的子集。explicit关键字可能会做到这一点,但不幸的是,VS2010不支持显式运算符。
operator bool(void) const;
add(Wrapper_A || Wrapper_B);
explicit operator bool(void) const;