You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何无法重载operator<<以输出test2 + test3的结果?

问题原因与解决方案

这问题的核心出在你的operator<<函数参数的引用类型上!

你当前的operator<<声明是:

std::ostream& operator <<(std::ostream& os, Stonewt& a)

第二个参数是非const的左值引用,而test2 + test3返回的是一个临时对象(右值)——C++的规则里,临时对象是不能绑定到非const的左值引用上的,所以编译器找不到能匹配std::cout << 临时对象的重载函数,自然就报错了。

那为什么std::cout << test4能正常工作?因为test4是一个具名的左值对象,它可以正常绑定到非const的左值引用上,所以编译器能找到对应的重载。

解决方法很简单:把参数改成const引用

既然输出操作根本不会修改Stonewt对象的内容,那完全可以把第二个参数声明为const Stonewt&,这样既符合逻辑,又能让临时对象(右值)绑定到这个const引用上。

修改后的友元函数如下:

std::ostream& operator <<(std::ostream& os, const Stonewt& a) {
    if (a.format == Stonewt::STONE) {
        os << "stone format" << '\n';
        os << a.stone << " stones " << a.pound << " pounds" << '\n';
    } else if (a.format == Stonewt::POUNDS) {
        os << "pounds format" << '\n';
        os << a.pounds << " pounds" << '\n';
    } else {
        os << "not valid" << '\n';
    }
    return os;
}

(顺便帮你修正了代码里的拼写错误valdid→valid😉)

修改之后,不管是输出具名对象test4,还是输出test2 + test3产生的临时对象,编译器都能找到正确的重载函数,两种场景都能正常工作了。

内容的提问来源于stack exchange,提问作者Youshikyou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:44:38