为什么重载运算符<<有时工作,但其他时间不工作

HRL*_*LTY 2 c++ overloading

我不知道为什么cout << da << '\n'工作正常,但出std::cout << next_Monday(da) << '\n'了问题.为什么直接Date对象可以输出,但返回Date不能.为什么operator <<有时超载工作,但有时则不工作.这是我的代码..

#include <iostream>
#include <stdlib.h>

struct Date {
    unsigned day_: 5;
    unsigned month_ : 4;
    int year_: 15;
};

std::ostream& operator<<(std::ostream& out,Date& b)
{
    out << b.month_ << '/' << b.day_ << '/' << b.year_;
    return out;
}

std::istream& operator>>(std::istream& in,Date& b);
Date next_Monday(Date const &d);

int main()
{
    Date da;
    std::cin >> da;
    std::cout << da << '\n';
    std::cout << next_Monday(da) << '\n';
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这就是clang所说的:(我用g ++来调用)

excercise19DateManipulate.cpp:114:18: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'Date') std::cout<< next_Monday(da) <<'\n'; ~~~~~~~~^ ~~~~~~~~~~~~~~~

jua*_*nza 6

因为您无法将临时绑定到非const左值引用.更改运算符以获取const参考:

std::ostream& operator<<(std::ostream& out, const Date& b)
Run Code Online (Sandbox Code Playgroud)