class foo {
public:
friend ostream& operator << (ostream &os, const foo &f);
foo(int n) : a(n) {}
private:
vector <int> a;
};
ostream& operator << (ostream &os, const foo &f) {
for (int i = 0; i < f.a.size(); ++i)
os << f.a[i] << " ";
os << endl; // why is this line a must?
}
int main(void) {
foo f(2);
cout << f << endl;
return 0;
}
上面代码中,如果去掉标记的那一行,会出现segment fault错误,谁能解释一下为什么?
最佳答案
ostream& operator << (ostream &os, const foo &f) {
for (int i = 0; i < f.a.size(); ++i)
os << f.a[i] << " ";
os << endl; // why is this line a must?
}
不是强制性的。段错误是因为您没有返回 os
ostream& operator << (ostream &os, const foo &f) {
for (int i = 0; i < f.a.size(); ++i)
os << f.a[i] << " ";
return os; // Here
}
如果您不返回 ostream,则为未定义行为。 endl
正在刷新您的 os
。这就是它看起来有效的原因。
编辑:根据 Bo Persson 的说法,为什么它在这种情况下有效
The os << endl; is another operator call that actually returns os by placing it "where a return value is expected" (likely a register). When the code returns another level to main, the reference to os is still there
关于c++ - 如果没有 endl,则重载 ostream 运算符段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15788672/