我有一个类似下面的const函数,需要检查文件流是否打开,然后才能继续执行:
bool MyClass::checkSomeStuff() const
{
// Where outputFile_ is a std::ofstream
if ( ! outputFile_.is_open() )
{
throw std::runtime_error( "Output file not open." );
}
// ... do more stuff
然而,看起来我无法这样做,因为is_open()
被声明为:
bool is_open ( );
在我看来,像这样明显是纯访问器的函数应该是非const的,这似乎有点奇怪。它背后的逻辑有意义吗?
const
流做什么? - NimcheckSomeStuff
函数是且应该是const——它是一个访问器。我不希望它因为is_open()
是非const而变成非const——这似乎不正确。 - Component 10outputFile.rdbuf()->is_open()
。 - Jonathan Wakely