【问题标题】:Return reference to local variable when overloading <<重载时返回对局部变量的引用<<
【发布时间】:2012-09-06 10:49:09
【问题描述】:

我是一名尝试学习 c++ 的初学者,所以我的问题可能非常基础。考虑以下代码:

class pounds
{
private:
    int m_p;
    int m_cents;
public:
    pounds(){m_p = 0; m_cents= 0;}
    pounds(int p, int cents) 
{
    m_p = p;
    m_cents = cents;
}

friend ostream& operator << (ostream&, pounds&);
friend istream& operator>>(istream&, pounds&);

};

ostream& operator<< (ostream& op, pounds& p)
{
    op<<p.m_p<<"and "<<p.m_cents<<endl;
    return op;
}

istream& operator>>(istream& ip, pounds& p)
{
    ip>>p.m_p>>p.m_cents;
    return ip;
}

这可以编译并且似乎可以工作,但我没有返回对局部变量的引用?提前致谢。

【问题讨论】:

  • 不,引用已经在参数中,并且引用了函数之外的东西,所以一切都很好。
  • 引用本身不是对象。您是否返回对本地的引用取决于原始引用所指的内容。在你的情况下没关系,因为 opip 指的是来自调用站点的对象。

标签: c++ operator-overloading pass-by-reference


【解决方案1】:

没错,既然没有局部变量,就有references,那会被传递,什么时候会调用operators

我建议您将operator &lt;&lt; 的签名更改为

std::ostream& operator << (ostream& os, const pounds& p);

因为p在功能上没有被修改。

【讨论】:

  • 非常感谢 ForEveR,我想我现在明白了。
最近更新 更多