【发布时间】:2015-06-29 18:30:29
【问题描述】:
我在玩一个类Foo,它定义了一个隐含的operator bool()。我使用Foo 作为多个函数的返回类型,因此我可以获得有关已完成操作的信息并调用Foo::operator bool() 以获取操作是否已成功执行。
出于好奇,我还尝试在使用Foo时显式调用转换运算符:
if(!func().operator bool()) // func returned Foo
throw std::logic_error("operation was not successful");
效果很好。然后,我突然决定转储Foo 类并使用简单的bool,但我忘记删除函数返回值上的.operator bool() 调用。于是我发现了 Visual C++ 12.0 编译器(Visual Studio 2013)的一组奇怪行为。
转换运算符对bool 的显式调用在 GCC 中均无效:request for member ‘operator bool’ in ‘true’, which is of non-class type ‘bool’
现在,我使用 Visual Studio 得到的行为:
#include <iostream>
using std::cout;
using std::endl;
bool func()
{
return true;
}
int main()
{
bool b = true.operator bool();
cout << b << endl; // error C4700: uninitialized local variable 'b' used
// evaluates to true (probably like b would do if it compiled)
if(false.operator bool())
cout << "a" << endl;
cout << func().operator bool() << endl; // prints nothing
int m = 10;
cout << m.operator int() << endl; // prints nothing
// correctly gives error: left of '.<' must have class/struct/union
cout << m.operator <(10) << endl;
}
即使是智能感知也是正确的并显示Error: expression must have a class type。
这一切有解释吗?一个错误? (不需要的)扩展?这是什么?
【问题讨论】:
标签: c++ visual-c++ visual-studio-2013 operators