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;
}
在上面的代码中,如果删除标记的行,就会出现段错误错误,有人可以解释为什么吗?
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 的说法,为什么它在这种情况下起作用
os
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)