gpt4 book ai didi

c++ - 重载 << 时返回对局部变量的引用

转载 作者:行者123 更新时间:2023-11-30 04:25:10 26 4
gpt4 key购买 nike

我是一名尝试学习 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;
}

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

最佳答案

没错,因为没有局部变量,所以有references , 当 operators 时,这将被通过将被调用。

我建议你更改 operator << 的签名到

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

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

关于c++ - 重载 << 时返回对局部变量的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12298407/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com