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? }
不是躁狂的.由于您没有返回操作系统而导致段错误
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在这里冲你的操作系统.这就是它似乎正在起作用的原因.
编辑:根据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