shi*_*ilk 6 c++ vector operator-overloading ostream
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;
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,如果标记的行被删除,会出现段错误,有人可以解释一下原因吗?
小智 17
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?
}
Run Code Online (Sandbox Code Playgroud)
不是躁狂的.由于您没有返回,因此导致了段错误os
ostream& operator << (ostream &os, const foo &f) {
for (int i = 0; i < f.a.size(); ++i)
os << f.a[i] << " ";
return os; // Here
}
Run Code Online (Sandbox Code Playgroud)
如果你不返回ostream,它是未定义的行为.这endl是在冲你的os.这就是它似乎正在起作用的原因.
编辑:根据Bo Persson,为什么它在这种情况下工作
os << endl; 是另一个操作符调用,实际上通过将其置于"预期返回值"(可能是寄存器)来返回操作系统.当代码返回另一个级别为main时,对os的引用仍然存在