简体   繁体   English

定义两个版本的 << 重载

[英]Defining two versions of << overload

Can someone tell me what is wrong when I try to overload << in a slightly different way by using another symbol like <<=当我尝试使用<<=之类的另一个符号以稍微不同的方式重载<<时,有人能告诉我出了什么问题吗?

#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
}

If I use如果我使用

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

It works fine, so what is the problem with adding in << '\n' when std::ostream& is returned by <<= ?它工作正常,那么在<<=返回 std::ostream& 时添加<< '\n'有什么问题?

Due to the operator precedence this statement由于运算符优先级,此语句

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

is equivalent to相当于

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

and the right most expression和最正确的表达

( date << '\n' )

produces an error because such an operator is not defined for objects of the type struct Date .产生错误,因为没有为struct Date类型的对象定义这样的运算符。

Thanks to Vlad from Moscow's answer,感谢莫斯科的弗拉德的回答,

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

is the simple fix.是简单的修复。 Not as pretty as was desired, but works correctly.没有预期的那么漂亮,但可以正常工作。 Perhaps defining a derived class DateAndTime of Date that has the hours, minutes, and seconds and then overloading << for DateAndTime may be a more elegant, but longer, solution.也许定义具有小时、分钟和秒的Date的派生 class DateAndTime然后为DateAndTime重载 << 可能是一个更优雅但更长的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM