在C++中,我可以像ifstream
对象一样使用我的对象作为测试表达式吗?若否,原因为何?
例如:
ifstream ifs ("myfile.txt");
while( ifs ){
//read and process data..
}
我有一个类,我需要重载哪个运算符才能让编译器允许我的对象作为测试表达式传递?
例如:
MyClass obj1;
if( obj1 ){
//do something..
}
while( obj1 ){
//do something repeatedly..
}
两者都应该是有效的表达式。
发布于 2013-02-19 15:12:38
您有几个选择。也许最好的方法是重载operator bool()
。如下所示:
class A{
public:
operator bool()
{
return flag;
}
private:
bool flag;
};
编辑:正如注释中所指出的,如果您使用C++11
,最好通过在前面添加explicit
关键字来显式地显示操作符。否则,使用operator void*()
可能更好
发布于 2013-02-19 15:12:53
您必须在您的类中实现bool
重载。如下所示:
class myClass {
public:
explicit operator bool() const { return condition; }
};
它可以在if
和while
语句中工作。但是,如果您的编译器不支持C++11,则不能在此重载中使用explicit
关键字。
发布于 2013-02-19 15:27:55
有很多选择。
您不必在类中实现operator bool
重载。
这通常不是最好的选择。
最佳:命名状态检查。
最好的方法是使用名为的状态检查方法。例如,iostreams具有fail
成员,因此您可以编写
while( !cin.fail() ) { ... }
对于您自己的类,它可能如下所示:
struct S
{
bool is_good() const { return ...; } // Whatever name.
};
So-so:将explicit
转换为bool
。
下一个最好的是explicit
转换运算符。将其设置为explicit
可防止if因将某个对象作为函数参数传递而被意外调用。条件中仍然使用explicit
转换运算符,因此可以这样写,例如
while( cin ) { ... }
它在C++11中调用一个
explicit operator bool () const { return !fail(); }
对于您自己的类,它可能看起来像这样
struct S
{
explicit operator bool () const { return ...; }
};
不好:隐式转换为"private“指针类型。
第三,如果您使用的编译器不支持explicit
转换,即C++03编译器,并且由于某种无法解释的原因,您不想要命名检查,这是最佳选择,那么您可以选择一种最大限度减少意外调用机会的结果类型。
在C++03中,iostreams使用了隐式转换为void*
(而不是bool
)。
有些人提倡使用“安全布尔法”,即在C++03中,结果是一个指向客户端代码无法访问的类型的指针。
绝对最糟糕的情况:隐式转换为bool
。
最糟糕的选择是
struct S
{
operator bool () { return ... }
};
有了这个
const
对象上调用const
转换。添加一个const
只会让它稍微不那么糟糕。
情况还是很糟糕。:-)
https://stackoverflow.com/questions/14960742
复制