if('fstream 对象')如何返回 true 或 false 的值,具体取决于文件是否已打开?
How does if ('fstream object') return a value of true or false depending on if the file was opened?
我很好奇fstream
class
如何通过简单地将对象的名称放在条件语句中来返回true
或false
值。例如。。。
std::fstream fileStream;
fileStream.open("somefile.ext");
if (!fileStream) // How does this work?
std::cout << "File could not be opened...n";
我问这个是因为如果我以类似的方式使用它,我希望我自己的类返回一个值。
这并不是说它等于真或假,而是它重载了!
运算符以返回其状态。
有关详细信息,请参阅 http://www.cplusplus.com/reference/iostream/ios/operatornot/。
自己执行此操作非常简单,请查看运算符重载常见问题解答或C++运算符重载指南。
编辑:有人向我指出,ios
还会重载void *
转换运算符,在失败时返回空指针。因此,您也可以使用这种方法,前面提到的常见问题解答中也介绍了这种方法。
这使用转换运算符工作。请注意,看似显而易见的方式,转换为bool
,具有意想不到的副作用,因此应使用转换为内置类型并隐式转换为bool
,例如:
class X
{
public:
void some_function(); // this is some member function you have anyway
operator void(X::*)() const
{
if (condition)
return &X::some_function; // "true"
else
return 0; // "false"
}
};
在 C++11 中,您可以转换为显式bool
,从而避免意外的副作用。因此,在 C++11 中,您可以简单地编写:
class X
{
public:
explicit operator bool() const
{
return condition;
}
};
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 奇怪的Arduino C++编译错误取决于文件位置
- read() 上的不同行为取决于写入不可写内存时表示文件、匿名管道或套接字的文件描述符
- C++程序行为取决于源代码文件集
- 关闭文件流时出错,其存在取决于与 C++ 中的 .close() 语句相同的布尔值
- 生成文件 C/C++,其功能取决于环境
- MACRO取决于其文件夹位置
- 视觉C++找不到库 - 取决于库文件夹顺序
- if('fstream 对象')如何返回 true 或 false 的值,具体取决于文件是否已打开?
- 可变长度数组,取决于文件C++的长度
- 编译后二进制文件的大小如何取决于所使用的库?c / c++
- c++对象文件的大小取决于什么?
- 如何从文本文件中只加载某些行,这取决于它们在C和c++中的开始方式