[英]Why << operator in ofstream is not const?
I noticed that the operator <<
in ofstream
is not const
. 我注意到
ofstream
中的operator <<
不是const
。 It is obvious that this operator will change the content of the file but what is it changing inside the ofstream
object? 很明显,这个操作符会改变文件的内容,但是它在
ofstream
对象中的变化是什么?
In other words, if I have ofstream
as a class member function and I want to call the << operator
on it inside a const
member function I have to alter it to non-const
member function or mark the ofstream
as mutable
but it seems not logical from abstract point of view for me.. did I miss something? 换句话说,如果我将
ofstream
作为类成员函数并且我想在const
成员函数内调用<< operator
,我必须将其更改non-const
成员函数或将ofstream
标记为mutable
但似乎不是从抽象的角度来看,对我来说是合乎逻辑的......我有没有想念?
Because it logically changes the stream. 因为它在逻辑上改变了流。 To the bare minimum, it changes the write position within the stream buffer.
至少,它改变了流缓冲区中的写入位置。 It can also modify the status of the stream (for example, when writing error happens).
它还可以修改流的状态(例如,发生写入错误时)。
But what is even more important (in my view) is the logical mutability. 但更重要的是(在我看来)是逻辑上的可变性。 The stream is not the same after the writing - it has the new value in it.
写入后流不一样 - 它具有新值。 If your class doesn't care about this fact, you may declare your stream member
mutable
. 如果您的班级不关心这一事实,您可以声明您的流成员是
mutable
。
因为它可以调用setstate()
而不是const
,因为它改变了对象的内部结构,如流的格式化部分所述 。
Keep in mind that while ofstream
itself doesn't have to be modified to be written to (even though it probably should), the ostringstream
which also inherits the <<
operator from ostream
class has to be modified in order to be written to, as you need to change the internal string
object. 请记住,虽然
ofstream
本身不需要被修改以便写入(即使它可能应该),但是也必须修改从ostream
类继承<<
运算符的ostringstream
才能被写入,如您需要更改内部string
对象。 Because of that, the operator has to be declared const
to cover all the cases (the operator is defined in ostream
class). 因此,必须将运算符声明为
const
以涵盖所有情况(运算符在ostream
类中定义)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.