0

当我尝试<<通过使用另一个符号(如<<=

#include <iostream>

struct Date { 
    int day, month, year, hour, minute, second;
    Date (int d, int m, int y, int h, int min, int s) { day = d;  month = m;  year = y;  hour = h;  minute = min;  second = s; }
    friend std::ostream& operator << (std::ostream&, const Date&);
    friend std::ostream& operator <<= (std::ostream&, const Date&);  // Carries out << but without the hour, minute, and second.
};

std::ostream& operator << (std::ostream& os, const Date& d) {
    os << d.day << ' ' << d.month << ' ' << d.year << ' ' << d.hour << ' ' << d.minute << ' ' << d.second;
    return os;
}

std::ostream& operator <<= (std::ostream& os, const Date& d) {
    os << d.day << ' ' << d.month << ' ' << d.year;
    return os;
}

int main () {     
    Date date(25, 12, 2021, 8, 30, 45);
    std::cout << "Today is " << date << '\n';  // Works fine
    std::cout << "Today is " <<= date << '\n';  // Does not work
}

如果我使用

std::cout << "Today is " <<= date;

它工作正常,那么<< '\n'当 std::ostream& 返回时添加有什么问题<<=

4

2 回答 2

4

由于运算符优先级,此语句

std::cout << "Today is " <<= date << '\n';

相当于

( std::cout << "Today is " ) <<= ( date << '\n' );

和最正确的表达

( date << '\n' )

产生错误,因为没有为 类型的对象定义这样的运算符struct Date

于 2021-12-25T19:14:59.007 回答
0

感谢莫斯科的弗拉德的回答,

(std::cout << "Today is " <<= date) << '\n';

是简单的修复。没有预期的那么漂亮,但可以正常工作。也许定义一个具有小时、分钟和秒的派生类DateAndTimeDate然后重载 << forDateAndTime可能是一个更优雅但更长的解决方案。

于 2021-12-25T19:29:29.670 回答