操作员过载以ostream无法与用户定义的类工作

发布于 2025-02-12 16:23:13 字数 497 浏览 1 评论 0原文

我有一个简单的程序,当我尝试 cout<< 75.0_STC; 我有多个错误,我不知道为什么。只有当我通过参考传递温度对象时,才会发生。

class temperature
{
    public:
        long double degrees;
        temperature(long double c): degrees{c}{}
        long double show()const {return degrees;}

};
temperature operator"" _stC(long double t){
    return temperature(t);
}
ostream & operator<<(ostream &ekran, temperature &t)
{
    ekran << t.show();
    return ekran;
}

I have this simple program and when i try to cout << 75.0_stC ; i have multiple errors and i don't know why.This things only happen when i pass my temperature object via reference.

class temperature
{
    public:
        long double degrees;
        temperature(long double c): degrees{c}{}
        long double show()const {return degrees;}

};
temperature operator"" _stC(long double t){
    return temperature(t);
}
ostream & operator<<(ostream &ekran, temperature &t)
{
    ekran << t.show();
    return ekran;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

离去的眼神 2025-02-19 16:23:13

您可能需要对要打印的参数进行const引用:

ostream & operator<<(ostream &ekran, const temperature &t)

临时性不会绑定到非const参考参数。

You likely need to take a const reference to the argument you'd like to print:

ostream & operator<<(ostream &ekran, const temperature &t)

Temporary won't bind to the non-const reference argument.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文