c – 如果没有endl,则重载ostream操作符分段错误

前端之家收集整理的这篇文章主要介绍了c – 如果没有endl,则重载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;
}

在上面的代码中,如果标记的行被删除,会出现段错误,有人可以解释一下原因吗?

解决方法

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

原文链接:https://www.f2er.com/c/117641.html

猜你在找的C&C++相关文章