在 C++ 中,我可以将我的对象用作测试表达式,如 ifstream
对象吗?如果不是,为什么?
例如
ifstream ifs ("myfile.txt");
while( ifs ){
//read and process data..
}
我有一个类,我需要重载哪个运算符才能让编译器允许我的对象作为测试表达式传递?
例如
MyClass obj1;
if( obj1 ){
//do something..
}
while( obj1 ){
//do something repeatedly..
}
两者都应该是有效的表达式。
最佳答案
您必须在您的类中实现一个bool
重载。像这样:
class myClass {
public:
explicit operator bool() const { return condition; }
};
它在 if
和 while
语句中都有效。但是,如果您的编译器不支持 C++11,则您不能在此重载中使用 explicit
关键字。
关于c++ - 是否可以将任何类对象作为任何测试表达式的测试表达式传递,例如 if,while like ifstream 对象。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14960742/