我有一个自定义类,我为其定义了一个自定义铸造操作员char()
,称其为 a
。现在,说我想要此类的数组,但是使用添加功能,因此我定义了一个新的类 b
,可以使用成员变量 array
std: :vector< a> 。
我想要处理 b
的一件事是将其数据打印到屏幕上,因此
ostream& operator<<(ostream& out, const B& b)
{
// invoking custom cast works fine here
for(int i=0;i<array.size();++i) out.put((char)array[i]);
// without the following out.flush() we get segfault
out.flush()
}
当我省略 out.flush()时,我出于某种原因 创建 friend
函数。
语句最后会导致分段故障。我宁愿在那里没有冲洗,因为它应该由用户选择何时冲洗流(我相信?),所以有人可以澄清为什么它没有它崩溃了吗?
谢谢!
I have a custom class for which I've defined a custom cast operator char()
, call it A
. Now, say I want an array of this class but with added functionality so I define a new class B
to achieve this with a member variable array
of type std::vector<A>
.
One of the things I want B
to handle is printing its data to screen so I create a friend
function
ostream& operator<<(ostream& out, const B& b)
{
// invoking custom cast works fine here
for(int i=0;i<array.size();++i) out.put((char)array[i]);
// without the following out.flush() we get segfault
out.flush()
}
For some reason when I omit the out.flush()
statement at the end it causes a segmentation fault. I would rather not have the flush in there because it should be up to the user to choose when to flush the stream (I believe?) so can anybody please clarify why it crashed without it?
Thanks!
发布评论
评论(1)
你必须在那里归还一些东西。当然你已经提供了流,所以你应该:
作为操作符的最后一行。请注意,也许偶然,调用
out.flush()
会创建一些寄存器(例如 EAX)来保存流的值,从而被返回(根据标准调用约定),这就是来电者正在等待。 但是你必须添加最后一个返回
。You have to return something there. Certainly the stream you've been provided, so you should:
as the last line of the operator. Note that, maybe by chance, calling
out.flush()
made some register (say EAX) to hold the value of the stream, thus being returned (as per standard calling convention), and this is what the caller was expecting. BUT you have to add that lastreturn
for sure.